YII:relations()自定义关联查询

Each kind of related objects is defined in this method as an array with the following elements:

'varName'=>array('relationType', 'className', 'foreignKey', ...additional options)
where 'varName' refers to the name of the variable/property that the related object(s) can
be accessed through;
'relationType' refers to the type of the relation, which can be one of the
following four constants: self::BELONGS_TO, self::HAS_ONE, self::HAS_MANY and self::MANY_MANY;
'className' refers to the name of the active record class that the related object(s) is of;
and 'foreignKey' states the foreign key that relates the two kinds of active record.
Note, for composite foreign keys, they can be either listed together, separated by commas or specified as an array
in format of array('key1','key2'). In case you need to specify custom PK->FK association you can define it as
array('fk'=>'pk'). For composite keys it will be array('fk_c1'=>'pk_с1','fk_c2'=>'pk_c2').
For foreign keys used in MANY_MANY relation, the joining table must be declared as well
(e.g. 'join_table(fk1, fk2)').

说明: 有时外键可能由两个或更多字段组成,在这里可以将多个字段名由逗号或空格分隔, 一并写在这里。对于多对多的关系,关联表必须在外键中注明,例如在Post 类的categories 关联中,外键就需要写成PostCategory(postID,categoryID)。

class Post extends CActiveRecord {
    public function relations() {
        return array(
            'author'=>array(
                self::BELONGS_TO,
                'User',
                'authorID'//外键,等同于array('authorID')
            ),
            'categories'=>array(
                self::MANY_MANY,
                'Category',
                'PostCategory(postID, categoryID)'//多对多关系
            ),
        );
    }
}

说明:若你需要指定自定义的关联,你可以把它定义为array('fk”= > 'pk”)。对于复合外键可以把它定义为 array('fk_c1'=>'pk_с1','fk_c2'=>'pk_c2')。

class User extends CActiveRecord {
    public function relations() {
        return array(
            'crm_presona_tree' => array( 
                self::HAS_ONE, 
                'CrmPresonaTree', 
                array('presona_id'=>'presona_id','usertype'=>'usertype'), //即user.presona_id=cpt.presona_id and user.usertype=cpt.usertype
                'alias' => 'cpt', 
                'together'=>false, 
            ),
        );
    }
}

你可能感兴趣的:(YII:relations()自定义关联查询)