2016-12-14 26 views
0

我有型號:A[id, value]B[id, value]X[id, a_id]。 我想找到X包含A和包含B其中B.value = A.value,都ABvalue字段是唯一的,所以只有一個行關係(如果有)。與不使用自定義的解決主鍵嵌套hasOne關係加入

$this->X->find('all', array(
    'contain' => array(
     'A' => array('B') 
    ) 
)); 

是我的嘗試是$belongsTo協會(在兩側)

'B' => array(
    'foreignKey' => false, 
    'conditions' => array(
     'A.value = B.value' 
    ) 
) 

在SQL日誌只有1=1WHERE部分。

有沒有可能解決它,而不使用joins,在單個查詢?

+0

如果有什麼不清楚或者我錯過了請告訴我 – Sojtin

回答

0

你必須使用

對於CakePHP的3.x的

的bindingKey:在當前表中的列,將被用於外鍵匹配的名稱。如果未指定,將使用主鍵 (例如Articles表的id列)。

正如http://book.cakephp.org/3.0/en/orm/associations.html

public $belongsTo = [ 
    'B' => [ 
     'foreignKey' => 'status', 
     'bindingKey'=>'status', 
    ] 
]; 

提到CakePHP的2.x的

associationForeignKey:在其他 模型中發現的外鍵的名稱。如果您需要定義多個HABTM 關係,這特別方便。此鍵的默認值爲其他模型的下劃線, 單數名稱,後綴爲'_id'。

正如http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

public $belongsTo = [ 
    'B' => [ 
     'foreignKey' => 'status', 
     'associationForeignKey'=>'status', 
    ] 
]; 

提到這將爲你

還要注意的是,默認的遞歸級別爲1 工作,所以你必須遞歸定義2如上面所提到的這個文檔 http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive

$this->X->find('all', array(
    'recursive' => 2, 
)); 
+0

不幸的是,在2.x版本中沒有這樣的'bindingKey' – Sojtin

+0

@Sojtin如果你的代碼是cakephp 2.x,我已經更新了我的cakephp 2.x和3.x版本的答案 –

+0

@Sojtin你如何使用包含在你的代碼中它爲cakephp 3.x –