2011-11-08 63 views
0

我有以下的數據庫表:的CakePHP中可容納的行爲未正常工作

products 
******** 
id 
title 
artist_id 

artists 
******* 
id 
profile 
rating 
person_id 

people 
****** 
id 
full_name 

以下模型協會:

Product Model 
************* 
public $belongsTo = array(
    'Artist' => array(
     'className' => 'Artist' 
     'foreignKey' => 'artist_id' 
    ) 
); 

Artist Model 
************ 
public $belongsTo = array(
    'Person' => array(
     'className' => 'Person' 
     'foreignKey' => 'person_id' 
    ) 
); 
public $hasMany = array(
    'Product' => array(
     'className' => 'Product' 
     'foreignKey' => 'product_id' 
    ) 
); 

Person Model 
************ 
public $hasOne = array(
    'Artist' => array(
     'className' => 'Artist' 
     'foreignKey' => 'person_id' 
    ) 
); 

我已經設置這三個模型的使用中可容納的行爲使用:

public $actsAs = array('Containable'); 

當我使用以下來獲得產品的細節隨着藝術IST的名字:

$this->Product->find('first', array('conditions' => array('Product.id' => $id), 'contain' => 'Person.full_name')) 

我得到警告:

Model "Product" is not associated with model "Person" 

,我只拿到產品的詳細信息,即沒有藝術家的名字。這是爲什麼發生?

回答

2

發生這種情況,因爲你是在Product模型調用find操作,並且Person直接相關Product,而是間接地,通過它關係到Artist。在這種情況下,您的contain陣列應該是這樣的:

$this->Product->find('first', array(
    'conditions' => array('Product.id' => $id), 
    'contain' => array('Artist' => 'Person.full_name') 
)); 

這將返回一個結果像

array(
    [Product] => array(...), 
    [Artist] => array(
     [Person] => array(
      'full_name' => '...' 
     ) 
    ) 
)