views:

210

answers:

1

Greetings,

I am trying to tear down query returned from find call using containable in CakePHP.

for example I have 2 models, User and Post. User hasMany Post.

Now when I am using containable on find call like so:

$User->id = 1;
$User->find('first', array(
    'fields' => array('id'),
    'contain' => array('Post')
))

It will not return the associated Post, instead will just return the id of the user.

It works however if I am trying to fetch the data the other way around. i.e this works:

   $Post->find('first', array(
        'fields' => array('id', 'user_id'),
        'conditions' => array('Post.user_id' => 1),
        'contain' => array('User')
    ))

this doesn't:

   $Post->find('first', array(
        'fields' => array('id'),
        'conditions' => array('Post.user_id' => 1),
        'contain' => array('User')
    ))

From the returned values I then suppose that for the containable to works, the foreignKey has to be in the fields.

How then would I be able to filter out the User fields on the first call as the association of user is stored in Post.user_id?

Any help is greatly appreciated! Thank's.

-aw

A: 

As larryb82 said you'll need to define the relationship in both directions in order to retrieve Posts data from the User model

A user has many posts. A post belongs to an user

CakePHP Doc example

Schaoulli