condition while making relation in YIi

我只是一个虾纸丫 提交于 2020-01-13 13:50:20

问题


Agent:

agent_id (primary key)

User:

f_id (foreign key)
type

I have created relation in this way

public function relations() {
    return array(
        'user' => array(self::HAS_ONE, 'Users', 'f_id'),
    );
}

But I want to add more conditions like join only if type=3 in User table.

thanks.


回答1:


add the condition on your relation

public function relations() {
    return array(
        'user' => array(self::HAS_ONE, 'Users', 'f_id', array(
            'condition' => 'user.type = :type',
            'params' => array(':type'=>3)
        )),
    );
}

http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-options




回答2:


There is no error like 'Property "CHasOneRelation.0" is not defined' if you use this:

public function relations()
{
    return array(
        'user' => array(
            self::HAS_ONE, 
            'Users', 
            'f_id',
            'on' => 'user.ref_type = :type', 
            'params' => array(':type' => 3))
    );
}

See this link: http://www.yiiframework.com/forum/index.php/topic/10185-using-relations-and-conditions/




回答3:


You should create a function to get user rather use lazy-load which would use more query even you do not use this relation.

public function getUser(){
    return Users::model()->find(array(
        'condition'=>'type = :type', 
        'params' => array(':type'=>3)
    ));  
}

By using this you could use cache function to cache query that relation does not support.

public function getUser(){
    return Users::model()->cache(1000)->find(array(
        'condition'=>'type = :type', 
        'params' => array(':type'=>3)
    ));  
}


来源:https://stackoverflow.com/questions/10891294/condition-while-making-relation-in-yii

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!