模型中的 Kohana ORM 自定义方法
我有这两个模型:
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();
问题是如何实现“总计”方法,该方法的作用如下:
return DB::select(array(DB::expr('SUM(qty * sign)'), 'total')) ->from($this->_tb) ->where('user', '=', $user_id) ->execute() ->total;
该方法计算用户的积分(可以是+积分和-积分)并返回可用积分的总量。只要我使用 ORM::factory 方法来创建用户对象,我就想以使用加载的资源而不是运行新查询的方式实现“total”方法(我编写了上面的查询来演示业务逻辑)。
有什么建议吗? :)
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:
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).
Any suggestions? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)