Try to use ‘on’ parameter, not ‘condition’ when defining a relation with a condition, especially in HAS_ONE relation.
Consider definition of the person that has bank accounts and sometimes has a main account:
public function relations()
{
return array(
'accounts'=>array(self::HAS_MANY, 'Account', 'userId'),
'mainAccount_good'=>array(self::HAS_ONE, 'Account', 'userId',
'on'=>'mainAccount_good.main=1'),
'mainAccount_wrong'=>array(self::HAS_ONE, 'Account', 'userId',
'condition'=>'mainAccount_wrong.main=1'),
'mainAccount_works_too'=>array(self::HAS_ONE, 'Account', 'userId',
'condition'=>'mainAccount_works_too.main=1 or mainAccount_works_too.main IS NULL'),
);
}
$people = Person::model()->with('mainAccount_good')->findAll();
Will work properly, because it will return people having or not having a mainAccount set because the condition main=1 is put in ON clause in the query.
People who don’t have a main account (an account with a field “main” set to “1”) will have null as the value of the mainAccount_good relation.
$people = Person::model()->with('mainAccount_wrong')->findAll();
Will not work properly, because the condition is put in WHERE clause at the end of the whole query and the whole query is filtered.
So it will return people with their accounts but only people who have "main" set to "1".
So people who don’t have a main account will be filtered out.
What if we don’t join tables and want to filter rows from just 1 table?
Consider loading a record by
$person = Person::model()->findByPK(1);
Lazy loading an relation with a condition defined by ‘on’ clause works too!
Yii properly converts ON clause to WHERE clause in the query.
$account = $person->mainAccount_good;
Of course
$account = $person->mainAccount_wrong;
will work properly this time because the condition is put in WHERE clause.
I have not tested using ‘together’=false parameter but i think above examples will be useful for some people… even those who don’t have a bank account
Best regards.