How to pass parameter to relational query in Yii

I have a MANY_MANY relationship:

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

I get the result - Myclass state in siteController:

 $obj->rel 

Is it possible (and how) to pass the: param parameter from the controller to the relation request?

+4
source share
2 answers

I am sure this is not possible, but what you want to do can be achieved in a different way.
Check out the following from the manual :

We can use the parameters of a dynamic relational query with both parameters () and an option. Dynamic parameters will overwrite existing parameters as specified in the relations () method ....

So your request could be something like this (if we want to use a high load 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 a lazy loading approach to execute a 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. Read the related guide. Ask for clarification if necessary.

Edit:
As mentioned in the comments below, some conditions can be placed in a model relation, and only additional conditions should be specified during the request. An additional condition is automatically AND 'ed for the model relation condition. This is contrary to the documentation. In any case, you can use the following code:

 // In the model 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 related documentation

+6
source

You can try "Parameterized Named Scopes":

 function relations() { return array( 'rel'=>array(self::MANY_MANY, 'MyClass','table(id_1,id_2)', 'condition'=>'some conditions') ) } public function relByFieldName($fieldValue=5) { $this->getDbCriteria()->mergeWith(array( 'with' => 'rel', 'condition' => 'field_name = :value', 'params' => array(':value' => $fieldValue) )); return $this; } 

Then you can use it as follows:

 $models=Model::model()->relByFieldName(100)->findAll(); 
+3
source

Source: https://habr.com/ru/post/1397820/


All Articles