美文网首页
YII:relations()自定义关联查询

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

作者: zhang_xinglong | 来源:发表于2017-05-18 18:40 被阅读0次

    Each kind of related objects is defined in this method as an array with the following elements:
    <pre>'varName'=>array('relationType', 'className', 'foreignKey', ...additional options)
    </pre> 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()自定义关联查询

          本文链接:https://www.haomeiwen.com/subject/bdzsxxtx.html