Reputation: 6241
I have the following database tables:
products
********
id
title
artist_id
artists
*******
id
profile
rating
person_id
people
******
id
full_name
With the following model associations:
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'
)
);
I have set each of the three models to use the Containable behaviour using:
public $actsAs = array('Containable');
When I use the following to get the product details along with the artist's name:
$this->Product->find('first', array('conditions' => array('Product.id' => $id), 'contain' => 'Person.full_name'))
I get the warning:
Model "Product" is not associated with model "Person"
And I only get the product details ie no artist's name. Why is this happening?
Upvotes: 0
Views: 957
Reputation: 4448
This is happening because you are calling the find
operation on the Product
model, and Person
is not directly related to Product
, but indirectly, by its relation to Artist
. In this case, your contain
array should be something like the following:
$this->Product->find('first', array(
'conditions' => array('Product.id' => $id),
'contain' => array('Artist' => 'Person.full_name')
));
This will return a result like
array(
[Product] => array(...),
[Artist] => array(
[Person] => array(
'full_name' => '...'
)
)
)
Upvotes: 2