Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter to relational query in Yii

Tags:

php

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:

$obj->rel

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

lvil


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):

$param='something';
$obj=SomeModel::model()->with(array(
'rel'=>array('condition'=>'some conditions AND field_name=:param',
             'params' => array(':param' => $param))
))->findAll();
// some more code
$obj->rel->attributeOne;

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

$param='something';
$obj=SomeModel::model()->findByPk(1);
$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.

Edit:
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');

Controller:

$param='something';
$obj=SomeModel::model()->with(array(
'rel'=>array('condition'=>'field_name=:param',
             'params' => array(':param' => $param))
))->findAll();

Also see this comment in the linked documentation

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

bool.dev