mbagiella
(Mbagiella)
September 11, 2013, 3:31pm
1
Hi,
I want to show all items that have at least one relation with the other related table:
Item
id
name
OtherItem
id
name
itemId
How can I select only the item with at least one relation with otherItem ?
foreach(Item::model()->findAll("should have at least one relation with otherItem") as $item){
echo $item->name;
}
Thanks
shgninc
(Shgninc)
September 11, 2013, 3:44pm
2
In model file, Item:
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'otherItem' => array(self::HAS_ONE, 'OtherItem', 'itemId' ),
);
}
And any where you need just write:
$Items = Item::model()->with->('otherItem')->findAll();
foreach ($Items as $item):
echo $item->name;
echo $item->otherItem->name;
endforeach;
I hope it work fine:D
If your relation is a HAS_MANY and you don’t want items without “otherItem” assigned force an inner join:
$items = Item::model()->with->(array('otherItem'=>array('joinType'=>'INNER JOIN','together'=>true))->findAll();