YII關聯查詢


原文鏈接:http://keshion.iteye.com/blog/1607994

一、多表關聯的配置 

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

兩個 AR 類之間的關系直接通過 AR 類所代表的數據表之間的關系相關聯。 從數據庫的角度來說,表 A 和 B 之間有三種關系:一對多(one-to-many,例如 tbl_user 和 tbl_post),一對一( one-to-one 例如 tbl_user 和 tbl_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_MANY 為 BELONGS_TO 和 HAS_MANY 的組合。 例如,Post 屬於多個(belongs to many) Category ,Category 有多個(has many) Post.

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

 

 

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

 

 

其中 VarName 是關系的名字;RelationType 指定關系類型,可以是一下四個常量之一: self::BELONGS_TOself::HAS_ONE,self::HAS_MANY and self::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次查詢,而后者只有一次。兩者的選擇視情況而定。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM