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

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, 
            ),
        );
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,425评论 0 23
  • 走向“死亡”,原来的思想不适用了!可我现在又不甘真的死了 ——那就别瞎逼逼? 呵呵,瘦死的骆驼比马大! 一个思想,...
    击空留影阅读 1,449评论 0 1
  • 人物简介 苏瑾年:17岁,拥有六块腹肌,帅气的脸蛋。跟苏子韩是兄弟。聪明义气但又高冷傲娇,只不过从来不对苏子韩高冷...
    苏瑾晨阅读 2,948评论 0 1
  • 总觉得什么都不懂的清明境界和堪破一切的清明境界是不能相提并论的,前者在后者面前确实过于简单和不堪一击,但却存在着后...
    鹿小秋阅读 3,110评论 8 2
  • 水是火 火亦是水 来自地心两千米的一碗热汤 以人为骨 可以 煮好人煮坏人煮天才煮庸才 时光一边喝它的汤 也吐它的骨...
    丹崖阅读 2,571评论 0 0