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)').
說明: 有時外鍵可能由兩個或更多字段組成担孔,在這里可以將多個字段名由逗號或空格分隔, 一并寫在這里吃警。對于多對多的關系糕篇,關聯(lián)表必須在外鍵中注明,例如在Post 類的categories 關聯(lián)中酌心,外鍵就需要寫成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)'//多對多關系
),
);
}
}
說明:若你需要指定自定義的關聯(lián)谒府,你可以把它定義為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,
),
);
}
}