After reading the “The Definitive Guide to Yii” on relational active records, I’m still confused as to how model relationships work and hoping someone can shed some light on the matter.
To help understand what I’m trying to acheive the following query will return exactly the result I’m trying to get via DAO (Database Access Objects).
SELECT Widgets_Table.id, Widgets_Table.name
FROM Widgets_Table
INNER JOIN Group_Has_Widget_Table ON Group_Has_Widget_Table.widget_id = Widgets_Table.id
INNER JOIN Group_Table ON Group_Table.id = Group_Has_Widget_Table.group_id
WHERE Group_Table.id = '1'
I have 3 tables. Widgets_Table, Groups_Table, Group_Has_Widget_Table with the following columns.
(I’ve simplified the tables for this post)
[Widgets_Table]
id (int)(key)
name (string)
[Groups_Table]
id (int)(key)
name (string)
[Group_Has_Widget_Table]
group_id (int)
widget_id(int)
My Yii DAO configuration is as follows:
The relation in my Widgets Model is:
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'groups'=>array(
self::MANY_MANY,
'Groups',
'Group_Has_Widget_Table(widget_id, group_id)'
),
);
}
The relation in my Groups Model is:
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'widgets'=>array(
self::MANY_MANY,
'Widgets',
'Group_Has_Widget_Table(group_id, widget_id)',
),
);
}
And the call in the controller is:
Widgets::model()->with(array(
'groups'=>array(
// I don't want to select groups
'select'=>false,
// but want to get only widgets that belong to the group with id 1
'joinType'=>'INNER JOIN',
'condition'=>'groups.id=1',
),
))->findAll($criteria);
But the above call returns all the widgets regardless of the groups.id=1 condition.
To summarise, the expected result is for all records in the Widgets_Table to be returned only if it belongs to the group that has the Group_Table.id equal to 1.