Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - Multiple relations to the same model

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?

like image 538
Jeppe Stougaard Avatar asked Nov 13 '22 18:11

Jeppe Stougaard


1 Answers

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])

like image 53
Afnan Bashir Avatar answered Nov 15 '22 07:11

Afnan Bashir