How to pass a parameter to relational query in Yii

2019-04-09 22:08发布

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?

标签: php yii
2条回答
做个烂人
2楼-- · 2019-04-09 22:33

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 this way:

$models=Model::model()->relByFieldName(100)->findAll();
查看更多
趁早两清
3楼-- · 2019-04-09 22:48

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

查看更多
登录 后发表回答