开发者

Using an associated models columns for virtualFields?

开发者 https://www.devze.com 2023-03-26 23:24 出处:网络
I have a User model and an Order model. User hasMany Order. The orders table has a user_id column as well as a total column.

I have a User model and an Order model. User hasMany Order.

The orders table has a user_id column as well as a total column.

I would like to have a virtulField on the User model that is the count of how many orders are associate with that user.

I would also like t开发者_如何学编程o have a virtualField on the User that is the sum of all the totals.

The only way I have been able to get this to work is like so:

public $virtualFields = array(
    'total_orders' => '(SELECT COUNT(orders.user_id) FROM orders WHERE orders.user_id = User.id AND orders.status != "void" GROUP BY orders.user_id)',
    'total_sales' => '(SELECT SUM(orders.total) FROM orders WHERE orders.user_id = User.id AND orders.status != "void" GROUP BY orders.user_id)',
);

I am not sure if this is the best solution though, is there a better way?


for total order: use counterCache with counterScope: http://book.cakephp.org/view/1033/counterCache-Cache-your-count

you still need virtualField for total sales though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号