model relation with condition

I have table1 and table2.

table1 has one table2, but there are foreign key with condition

table1.key = table2.key would be "normal" foreign key, but there is also extra condition table2.area = "table1area" (predefined value)

How to create model relations properly for table1 (has one) and table2 (belongs_to)?

You can specify additional parameters for a relation (including condition). Read API for more info & examples.

At first it seemed that everything works fine, however, now I am stuck with the following problem:

if I add condition to rule, then $model->with doesn’t work as expected.

For example:

  • my model name is PolicyModel and it contains a lot of rules, some of them:



'holder'=>array(self::BELONGS_TO, 'ClientModel', 'holder_id'),

'document'=>array(self::HAS_ONE, 'DocumentModel', 'key', 'condition'=>'document.area="1"'),

[...]



Then I am trying to get Policy data by id:




    $policy_model=PolicyModel::model()->with('holder', ['...'], 'document')->findByPk($id);    



And this always returns me null. This is because condition "‘condition’=>'document.area=“1” is added at the end of select statement to get policy data. Something like:

select * from policy {joins} where document.area = "1"

So, by this query if no policies with document.area = 1 exist, then result is null.

However, the expected result was policy with given id and with empty $policy->document.