简体   繁体   English

Kohana ORM模型中的自定义方法

[英]Kohana ORM custom methods in models

I have these two models: 我有这两个模型:

class Model_user extends ORM {
    protected $_has_many = array('credits', array('model'=>'credit', 'foreign_key'=>'user'));
}

class Model_credit extends ORM {
    protected $_belongs_to = array('user', array('model'=>'user', 'foreign_key'=>'user'));
    protected $_tb = 'credits';
    protected $_pk = 'id'; 
    // method to be implemented
    public function total() {
        return $total_credits_available;
    }
}

// accessing the 'total' method
$user = ORM::factory('user', 1);
$total_credits = $user->credits->total();

The thing is how to implement the 'total' method, which does something like: 问题是如何实现'total'方法,它具有以下特点:

return DB::select(array(DB::expr('SUM(qty * sign)'), 'total'))
    ->from($this->_tb)
    ->where('user', '=', $user_id)
    ->execute()
    ->total;

The method counts users's credits (it can be +credits and -credits) and return the total amount of credits available. 该方法计算用户的信用(可以是+信用和 - 信用)并返回可用信用总额。 As long as I use ORM::factory method to create the user object, I'd like to implement the 'total' method in such manner it uses loaded resources rather than running a new query (I wrote the above query to demonstrate the business logic). 只要我使用ORM :: factory方法创建用户对象,我就想以这样的方式实现'total'方法,它使用加载的资源而不是运行新的查询(我写了上面的查询来演示业务逻辑)。

Any suggestions? 有什么建议? :) :)

<?php
class Model_user extends ORM {

        protected static $_totals = array();

        protected $_has_many = array('credits', array('model'=>'credit', 'foreign_key'=>'user'));

        public function total()
        {
            $total = Arr::get(Model_User::$_totals, $this->id, FALSE);

            if ($total !== FALSE)
                return $total;

            return Model_User::$_totals[$this->id] = $this->credits
                ->select(array(DB::expr('SUM(qty * sign)'), 'total'))
                ->find()
                ->total;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM