Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How to pass a parameter to relational query in Yii




I have a MANY_MANY relation:

'rel'=>array(self::MANY_MANY, 'MyClass','table(id_1,id_2)',  
             'condition'=>'some condiotions AND field_name=:param')

I get the result -instances of Myclass in the siteController:


Is it possible (and how) to pass the :param from the controller to the relation's query?

like image 667
lvil Avatar asked Dec 28 '22 05:12


1 Answers

I'm pretty sure that it's not possible, but what you want to do can be achieved in a different way.
Check the following from the Guide:

We can use dynamic relational query options in both with() and the with option. The dynamic options will overwrite existing options as specified in the relations() method. ...

So your query could be something like this (if we want to use eager loading approach):

'rel'=>array('condition'=>'some conditions AND field_name=:param',
             'params' => array(':param' => $param))
// some more code

Or when using the lazy loading approach to perform relational query:

$rels=$obj->rel(array('condition'=>'some conditions AND field_name=:param',
                      'params' => array(':param' => $param)

Hope this helps. Do read the linked guide. Ask for clarifications, if needed.

As already mentioned in the comments below, some conditions can be put in the model's relation, and only additional conditions need to be specified while querying. The additional condition is automatically AND 'ed to the model's relation condition. This seems contrary to the documentation. Anyway the following code can be used:

// In the model's relation:
'rel'=>array(self::MANY_MANY, 'MyClass','table(id_1,id_2)',  
         'condition'=>'some conditions');


             'params' => array(':param' => $param))

Also see this comment in the linked documentation

like image 126
bool.dev Avatar answered Jan 10 '23 18:01