PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 17, 2022

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

 March 17, 2022     cakephp     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing