Thursday, March 17, 2022

[FIXED] CakePHP - How to retrieve deeply associated data?

Issue

I have the following models:

User:

  • hasOne Profile, Page
  • hasMany Comment

Comment:

  • belongsTo User, Page, Profile

Page:

  • belongsTo User
  • hasMany Comment

Profile:

  • belongsTo User

When I retrieve a page, I want to get the associated Comments, and for each comment I want the Profile.

My comments table has fields page_id and user_id. My profile table has user_id.

So, I assume I need to do something like

Comment belongsTo 
'Profile' => array(
        'conditions' => array('Profile.user_id' => 'Comment.user_id')
    )

but that's not working - it returns a blank profile record.

I am using CakePHP 2.0.


Solution

Use CakePHP's Containable behavior [link]. Basically, this allows you to pick and choose which related models you want to include in your find.

You can also specify which field(s) you want from each model, specify conditions on each...etc.

It should look something like this:

//PageModel

public $actsAs = array('Containable');

public function getPage($id=null) {
    $this->recursive = -1;  //often set to -1 in the AppModel to make -1 the default
    $this->find('all', array(
        'conditions' => array(
            'Page.id' => $id
        ),
        'contain' => array(
            'Comment' => array(
                'User' => array(
                    'Profile',
                ),
            ),
        )
    ));

}


Answered By - Dave

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.