簡體   English   中英

Kohana ORM模型中的自定義方法

[英]Kohana ORM custom methods in 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();

問題是如何實現'total'方法,它具有以下特點:

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

該方法計算用戶的信用(可以是+信用和 - 信用)並返回可用信用總額。 只要我使用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;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM