【问题标题】:Kohana ORM custom methods in models模型中的 Kohana ORM 自定义方法
【发布时间】:2011-06-18 13:37:33
【问题描述】:

我有这两个模型:

类 Model_user 扩展 ORM { protected $_has_many = array('credits', array('model'=>'credit', 'foreign_key'=>'user')); } 类 Model_credit 扩展 ORM { protected $_belongs_to = array('user', array('model'=>'user', 'foreign_key'=>'user')); 受保护的 $_tb = '学分'; 受保护的 $_pk = 'id'; // 要实现的方法 公共功能总计(){ 返回$total_credits_available; } } // 访问 'total' 方法 $user = ORM::factory('user', 1); $total_credits = $user->credits->total();

问题是如何实现 'total' 方法,它的作用类似于:

返回 DB::select(array(DB::expr('SUM(qty * sign)'), 'total')) ->从($this->_tb) ->where('user', '=', $user_id) ->执行() ->总计;

该方法计算用户的信用(可以是+信用和-信用)并返回可用信用的总金额。只要我使用 ORM::factory 方法来创建用户对象,我想以这种方式实现“total”方法,它使用加载的资源而不是运行新的查询(我写了上面的查询来演示业务逻辑)。

有什么建议吗? :)

【问题讨论】:

    标签: php orm model kohana kohana-3


    【解决方案1】:
    <?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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多