yii relations 兩表關聯查詢

原文網址: http://keshion.iteye.com/blog/1607994

一、多表關聯的配置

 

在我們使用 AR 執行關聯查詢之前,我們需要讓 AR 知道一個 AR 類是怎樣關聯到另一個的。

兩個 AR 類之間的關係直接通過 AR 類所代表的數據表之間的關係相關聯。從數據庫的角度來說,表 A 和 B 之間有三種關係:一對多(one-to-many,例如 tbl_usertbl_post),一對一( one-to-one 例如tbl_usertbl_profile)和 多對多(many-to-many 例如 tbl_category tbl_post)。在 AR 中,有四種關係:

  • BELONGS_TO(屬於): 如果表 A 和 B 之間的關係是一對多,則 表 B 屬於 表 A (例如 Post 屬於 User);

  • HAS_MANY(有多個): 如果表 A 和 B 之間的關係是一對多,則 A 有多個 B (例如 User 有多個 Post);

  • HAS_ONE(有一個): 這是 HAS_MANY 的一個特例,A 最多有一個 B (例如 User 最多有一個 Profile);

  • MANY_MANY: 這個對應於數據庫中的 多對多 關係。 由於多數 DBMS 不直接支持 多對多 關係,因此需要有一個關聯表將 多對多 關係分割爲 一對多 關係。在我們的示例數據結構中,tbl_post_category 就是用於此目的的。在 AR 術語中,我們可以解釋 MANY_MANYBELONGS_TOHAS_MANY 的組合。例如,Post 屬於多個(belongs to many) CategoryCategory 有多個(has many) Post.

AR 中定義關係需要覆蓋 CActiveRecord 中的 relations() 方法。此方法返回一個關係配置數組。每個數組元素通過如下格式表示一個單一的關係。

 

 

Php代碼  收藏代碼
  1. 'VarName'=>array('RelationType''ClassName''ForeignKey', ...additional options)  

 

 

其中 VarName 是關係的名字;RelationType 指定關係類型,可以是一下四個常量之一:self::BELONGS_TO, self::HAS_ONE, self::HAS_MANY andself::MANY_MANYClassName 是此 AR 類所關聯的 AR 類的名字;ForeignKey 指定關係中使用的外鍵(一個或多個)。

 

需要弄清楚的幾點: 
(1),VarName指什麼?  詳見下面例2。 
(2),RelationType。一共有4種,分別爲

 

Php代碼  收藏代碼
  1. self::HAS_MANY, self::BELONGS_TO, self::MANY_MANY, self::HAS_ONE。   

 

 
(3),ClassName。即關聯的另一個../model/類名.php。 
(4),ForeignKey。誰是誰的外鍵? 
(5),附加條件 

 

ER Diagram

 

例1,一對多與多對一關係(post和user之間的關係)

1)models/Post.php

 

Php代碼  收藏代碼
  1. class Post extends CActiveRecord  
  2. {  
  3.     ......  
  4.    
  5.     public function relations()  
  6.     {  
  7.         return array(  
  8.             'author'=>array(self::BELONGS_TO, 'User''author_id'),  
  9.         );  
  10.     }  
  11. }  

 

 

其中Post與User的關係是BELONGS_TO(多對一)關係,並通過Post的author_id與User關聯。 
Post中author_id是外鍵,關聯到User中。 
注:此處的VarName是author,一個對象。

 

(2)models/User.php 

 

Php代碼  收藏代碼
  1. class User extends CActiveRecord   
  2. {   
  3.     ......   
  4.   
  5.     public function relations()   
  6.     {   
  7.         return array(   
  8.             'posts'=>array(self::HAS_MANY, 'Post''author_id'),   
  9.             'profile'=>array(self::HAS_ONE, 'Profile''owner_id'),   
  10.         );   
  11.     }   
  12. }   
 

 

 對於User,與Post的關係是屬於HAS_MANY(一對多)關係。並通過Post的author_id與Post關聯。

 

例2,多對多關係 
在FailParts.php中 

Php代碼  收藏代碼
  1. 'Users' => array(self::MANY_MANY, 'User''fail_parts_user(fail_parts_id, user_id)'),  

在User.php中 
Php代碼  收藏代碼
  1. 'FailParts' => array(self::MANY_MANY, 'FailParts''fail_parts_user(user_id, fail_parts_id)'),  


由於兩者是多對多關係,所以要用Users,而不是User;要用FailParts,而不是FailPart。 

此處的Users和FailParts,即爲前面的VarName。 

 

例3,一對一關係 
比較簡單,暫略。 

2,關於VarName。 
對於類A.php,'VarName'=>array('RelationType', 'B', 'ForeignKey', ...additional options) 
其中VarName與B基本相同。但未必完全一樣。此時就可以在A的views/A/xx.php中通過VarName來訪問B及其屬性值了。 

如果是一對一:A->VarName 
如果是多對一:author_name = $post->Author->name; 
如果是一對多:$posts  =  $author->Post; 
如果是多對多:$posts  =  $author->Post;//本質是拆成一對多和多對一

 

Php代碼  收藏代碼
  1. foreach($posts as $u){   
  2.    $_tmp_titles[] = $u -> title;   
  3. }   
  4. titleStr = implode(', '$_tmp_titles);   
 

二、多表關聯的使用 
常常在controllers裏 
1,延時加載 
(1)多對一 
$post = Post::model()->findByPk(10); 
$author = $post->author; 
批註:此處本質是一對一。 

(2)一對多 
$user = User::model()->findByPk(10); 
$posts = $user->posts; 

(3)多對多 
需要重點注意:兩個id有先後關係。 
站在$repairInfo實例的角度,關聯關係必須是 

Php代碼  收藏代碼
  1. 'FailParts' => array(self::MANY_MANY, 'FailParts''repair_mapping(repair_info_id,fail_parts_id)'),  

而站在$failParts實例的角度,則關聯關係變爲 
Php代碼  收藏代碼
  1. 'RepairInfos' => array(self::MANY_MANY, 'RepairInfo''repair_mapping(fail_parts_id, repair_info_id)'),  


而前面也已經指出,不需要雙方都配置,只需需要的一方設置即可。

 

之前曾使用過的笨方法: 

Php代碼  收藏代碼
  1. /*方法一:使用表關係(多對多)*/  
  2. $fails = $repairInfo->FailParts;//在$repairInfo中使用  
  3.  /*方法二:使用原始方法*/  
  4. $id = $repairInfo->id;  
  5. $maps = RepairMapping::model()->findAll("repair_info_id = $id");  
  6. $f_ids = array();  
  7. foreach($maps as $map){  
  8.     array_push($f_ids$maps[0]->fail_parts_id);  
  9.  }  
  10. $f_idsStr = implode(',',$f_ids);  
  11. $fails = FailParts::model()->findAll("id IN ($f_idsStr)");  


2,主動加載——with 
(1)一對多 
(2)多對多 
$posts = Post::model()->('author')->findAll(); 

例子: 
User.php 
Php代碼  收藏代碼
  1. //查詢一個機房$idc_id的所有用戶  
  2. function getAdminedUsersByIdc($idc_id){  
  3.   $c = new CDbCriteria();  
  4.   $c->join = "JOIN idc_user on t.id=idc_user.user_id";  
  5.   $c->condition = "idc_user.idc_id=$idc_id";  
  6.   return User::model()->with('Idcs')->findAll($c);  
  7. }  
  8. //規則中配置  
  9. 'Idcs' => array(self::MANY_MANY, 'Idc''idc_user(user_id, idc_id)'),  

批註:沒有with('Idcs'),執行後的結果也一樣。只不過不再是eager loading。 

三、帶參數的關聯配置 

常見的條件有 
1,condition      按某個表的某個字段加過濾條件 


例如: 
Php代碼  收藏代碼
  1. //在User的model裏定義,如下關聯關係  
  2. 'doingOutsources' => array(self::MANY_MANY, 'Outsource''outsource_user(user_id, outsource_id)',   
  3.       'condition' => "doingOutsources.status_id IN(" . Status::ASSIGNED . "," . Status::STARTED ."," . Status::REJECTED .")"),  
  4. //結論:condition是array裏指定model的一個字段。  

顯然,doingOutsources是真實數據表Outsource的別名,所以在condition中可以使用doingOutsources.status_id,當然也可以使用Outsource.status_id。另本表名user的默認別名是t。 

2,order             按某個表的某個字段升序或降序 
Php代碼  收藏代碼
  1. //在RepairInfo的model裏定義,如下關聯關係  
  2. 'WorkSheet'  => array(self::HAS_MANY, 'WorkSheet''repair_info_id', order => 'created_at desc'),  
  3. //調用  
  4. $worksheets = $repair_info->WorkSheet; //此時$worksheets是按降序排列  
  5. //結論:order是array裏指定model的一個字段。  

with 
joinType 
select 
params 
on 
alias 
together 
group 
having 
index 

還有用於lazy loading的 
limit        只取5個或10個 
offset 
through 
官方手冊 
'posts'=>array(self::HAS_MANY, 'post', 'author_id',     'order'=>'posts.create_time DESC', 'with'=>'categories'),

四、靜態查詢(僅用於HAS_MANY和MANY_MANY) 
關鍵字:self:STAT 
1,基本用法。例如, 
class Post extends CActiveRecord 

    ...... 

    public function relations() 
    { 
        return array( 
            'commentCount'=>array(self::STAT, 'Comment', 'post_id'), 
            'categoryCount'=>array(self::STAT,'Category','post_category(post_id, category_id)'); 

        ); 
    } 

2,靜態查詢也支持上面的各種條件查詢 
如 
Php代碼  收藏代碼
  1. 'doingOutsourceCount' => array(self::STAT, 'Outsource''outsource_user(user_id, outsource_id)',   
  2.                                     'condition' => "outsource.status_id IN(" . Status::ASSIGNED . "," . Status::STARTED ."," . Status::REJECTED .")"),  

其他查詢還包括 
condition  使用較多 
order 
select 
defaultValue 
params 
group 
having 

3,靜態查詢的加載方式 
可以使用lazy loading方式 
$post->commentCount. 
也可以使用eager loading方式 
$posts = Post::model()->with('commentCount','categoryCount')->findAll(); 
注with中字符串一定是別名。 

兩者的性能比較: 
如果需要取所有post的所有comment,前者需要2N+1次查詢,而後者只有一次。兩者的選擇視情況而定。

 

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章