Php Kohana ORM模型中的自定义方法

Php Kohana ORM模型中的自定义方法,php,orm,model,kohana,kohana-3,Php,Orm,Model,Kohana,Kohana 3,我有这两种型号: 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'=

我有这两种型号:

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(); 类模型\用户扩展ORM{ 受保护的$有\u many=array('credits',array('model'=>'credit','foreign\u key'=>'user'); } 类模型{ 受保护的$属于=数组('user',数组('model'=>'user','foreign'=>'user'); 受保护的$_tb='信用'; 受保护的$_pk='id'; //要实现的方法 公共职能总计(){ 返回$total_credits_可用; } } //访问“总计”方法 $user=ORM::工厂('user',1); $total_credits=$user->credits->total(); 问题是如何实现“total”方法,它的作用如下:

return DB::select(array(DB::expr('SUM(qty * sign)'), 'total')) ->from($this->_tb) ->where('user', '=', $user_id) ->execute() ->total; 返回DB::select(数组(DB::expr('SUM(数量*符号)'),'total')) ->从($this->\u tb) ->其中('user','=',$user\u id) ->执行() ->总数; 该方法计算用户的信用(可以是+信用和-信用)并返回可用信用的总量。只要我使用ORM::factory方法来创建用户对象,我就希望以这样的方式实现“total”方法:它使用加载的资源,而不是运行新的查询(我编写上述查询是为了演示业务逻辑)

有什么建议吗?:)


<?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;
        }
    }