hasOne link between models and addCondition


#1

Good afternoon,
I have three models group, material and layer. Model layer has hasOne link to the model material. Model material has hasOne link to the model group. On the input page for layer I would like to show only the materials of group that the user has previously selected. I’ve tried something like this:

$l = $this->add('Model_Layer'); 
$l_material = $ms -> refSQL('Material');
$l_material -> addCondition('group_id',$_GET['group_id']);

However it seems that something like this only works when there is hasMany connection between models. How could this be solved?

Thank you in advance


#2

Two ways as solution
One:

$l = $this->add('Model_Layer');
$j = $l->leftJoin('meterial_table_not_model','meterial_id_field_in_layer_table');
$j->addField('group_id'); // added in $j but is accessible in $l for conditions
$l->addCondition('group_id',$_GET['group_id']);

I used leftJoin here instead of Join : Reason: If you delete any model object that has join with other tables that records will be deleted as well.

Two:

$l= $this->add('Model_Layer');
$l->addExpression('group_id')->set($l->refSQL('material_id')->fieldQuery('group_id')); // If required frequently can add this in the model itself
$l->addCondition('group_id',$_GET['group_id']);

===
Note:
If updated recently from github master branch expressions will not be entertained in addCondition as calculated function in class Field is now deprecated… though needed a lot …


#3

you can use refSQL('material_id') if you want to traverse through hasOne() reference.