2011-11-29 124 views
2

假設我們有3種型號,用戶,衆議院和個人資料與他們之間的以下關聯:CakePHP:如何根據第二級關聯條件查詢結果?

  • 用戶的hasMany屋(樓屬於關聯用戶)
  • 用戶hasOne檔案(檔案屬於關聯用戶)

我想查詢房屋(在HousesController類內),其關聯的配置文件滿足給定的配置文件條件。請看下面的例子:

假設性別是剖面模型的屬性,我想檢索所有的房屋,其所有者是男性。

我發現this的問題,這是足夠接近我尋找。在我的情況下,模型之間的關係更復雜(House belongsTo User hasOne Profile),我無法使其工作。我已經試過這樣的事情,沒有任何的運氣:

$this->House->find('all', array(
        'contain' => array(
         'User' => array(
          'Profile' => array(
           'conditions' => array(
            'Profile.gender' => 'male' 
)))))); 

以上調用返回所有的房屋,並在案件中的性別是男的,它包括在結果的各個用戶的個人資料。否則,用戶個人資料將保持爲空。我真正需要的是返回只有房主是男性。

我已經實際使用'連接'選項Model::find()函數實現它,但我想知道是否可能沒有使用'連接',如果是,如何?

回答

2

我會建議明確宣佈使用bindModel法的關係。

你可以從你的房子做控制器像這樣:

/** 
* Bind the models together using explicit conditions 
*/ 
$this->House->bindModel(array(
    'belongsTo' => array(
    'User' => array(
     'foreignKey' => false, 
     'conditions' => array('House.user_id = User.id') 
    ), 
    'Profile' => array(
     'foreignKey' => false, 
     'conditions' => array('Profile.user_id = User.id') 
    ) 
) 
)); 

/** 
* Standard find, specifying 'Profile.gender' => 'male' 
*/ 
$houses = $this->House->find('all', array(
    'conditions' => array(
    'Profile.gender' => 'male' 
) 
)); 
+1

謝謝你這個答案。這正是我正在尋找的! 我想補充一點,如果你想使用paginate而不是find,Model :: bindModel()函數的第二個參數必須設置爲false。 – recu

相關問題