Yii 四種關聯關係:BELONGS_TO、HAS_ONE、HAS_MANY、MANY_MANY,搭配 with() 實現急切載入。
| 關係 | 含義 | 範例 | 參數順序 |
|---|---|---|---|
| BELONGS_TO | 屬於(多對一) | Post 屬於 User | 關聯表、外鍵欄位(主表存子表 PK) |
| HAS_ONE | 有一個(一對一) | User 有一個 Profile | 關聯表、外鍵欄位(子表存主表 PK) |
| HAS_MANY | 有多個(一對多) | User 有多個 Post | 關聯表、外鍵欄位(子表存主表 PK) |
| MANY_MANY | 多對多 | Post 與 Tag | 關聯表、中介表(關聯欄位) |
Model 定義
return array(
'author' => array(self::BELONGS_TO, 'User', 'author_id'),
'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'with' => 'author', 'order' => 'create_time DESC'),
'tags' => array(self::MANY_MANY, 'Tag', 'post_tag(post_id, tag_id)', 'order' => 'name'),
);
Controller 使用
$posts = Post::model()->with('author', 'comments', 'tags')->findAll();
select:指定查詢欄位 'select' => 'id,title'condition:額外條件 'condition' => 'status=1'limit/offset:限制筆數(不適用 BELONGS_TO)group/having:分組查詢(僅 HAS_MANY、MANY_MANY)through:中介模型(1.1.7+,僅 HAS_ONE、HAS_MANY)善用 with() 可避免 N+1 查詢問題,大幅提升關聯資料讀取效能。