Hello,
Considering I have three models :
-
User (id, name)
-
Items (id, name)
-
UserItems (id, user_id, item_id, quantity)
with the right relations to make User::Model()->with(‘items’) work as expected.
Somewhere in my page I want to display all the items with the quantity the current user owns next to it.
$user = User::Model()->with('items')->findByPk(1);
$items = Item::Model()->findAll();
// Here i display some users general informations
foreach ($items as $item) {
$user_item = $user->items->findByAttributes(array('id'=>$item->id)); // This line does not work
$user_item_quantity = $user_item ? $user_item->quantity : 0;
}
That, of course does not work
Another solution that should work would be:
foreach ($items as $item) {
$user_item = $user->items(array('condition'=>'id=$item->id'));
$user_item_quantity = $user_item ? $user_item[0]->quantity : 0;
}
Do you think of any elegant way to do this without firing too many SQL queries ? Are there any other syntax ?
Thanks for your feedback.