5
votes

How can I in YII get the related model for each time it has been associated to a given model or at least get a count for how many times it has happened?

The problem:
I have a table of Orders and a table of Products.
Each product is associated to the order 0 or more times.

How do I through the standard relational tool in YII tell how many times a product is on an order?
I have created a many-to-many relationship through a joint-table and use it to declare my relations

'products'=>array(self::MANY_MANY, 'Product', 'index_order_products(order_id, product_id)')

Problem is when I call $order->products it only returns the unique products, not a product for each time it is related.

I only need to know how many there are of each product on the order, so I've tried

'products'=>array(self::MANY_MANY, 'Product', 'index_order_products(order_id, product_id)', 'select'=>'*, COUNT(product_id) as count', 'group'=>'product_id')

But if I then try calling $order->products[0]->count it says count hasn't been defined.
I've managed to circumvent this by creating a empty column count in the database. This way I get the number I need, but surely there must be a better way.

What would be the correct way of doing something like this in YII?

2
@afnan-bashir I thought about using a statistical query, but I can't figure out how or where to define it. If I define it in Orders I will get a count of all products associated to the order, not for each individual product on the order. And it doesn't seem to make sense to define it on Products since it only exists in the context of the order - Jeppe Stougaard

2 Answers

1
votes

Well correct way would be using Statistical Query . It is for these purposes.

The non elegant way

But if I then try calling $order->products[0]->count it says count hasn't been defined.

this is because you are accessing count from object that is not returned when relation was evaluated. Use CVarDumper::Dump($order->products) to see what you get in case of query

or the other way could be count($order->products[0])

0
votes

For use this you do need define count property in Product class

'products'=>array(self::MANY_MANY, 'Product', 'index_order_products(order_id, product_id)', 'select'=>'*, COUNT(product_id) as count', 'group'=>'product_id')

 class Product extend CActiveRecord {
     public $count = 0;
 // skip in rules function add this
     array('count', 'safe'),