2
votes

I have 3 tables: Users, Profiles and Posts.

A User may have one Profile, and a Profile must have a User, a Post must have a User, and User may have many Posts. I have set this up in my Models and it all seems to work fine.

However when viewing a list of posts I am trying to show the Author firstname which is stored in the Profile table. But it's the User and Post table that are linked, and then the User table is linked to the Profile table. So their is no direct relation between the Post and the Profile.

How do I get this information?

Currently I'm trying to show this in the view with: <?php echo $post['Profile']['firstname']; ?> but because their is no direct association between the post and profile it does not work and I get the error: Undefined index: Profile

I have tried to do:

public function index()
    {
        $this->Post->recursive = 2;
        $this->set('posts', $this->paginate('Post'));
    }

but still no luck on getting the rest of the associations to come through!

Can anyone help? Thanks

1

1 Answers

0
votes

There are two ways to do this. One way to accomplish this is to join tables on the fly. The other way to do this is with the containable behaviour.

To use the containable behaviour you must add var $actsAs = array('Containable'); to all the models involved (or AppModel if you use it a lot). Then you can something like this in the controller:

    $post = $this->Post->find('first', array(
        'conditions' => array('id' => $id),
        'contain' => array('User' => 'Profile')         
    ));

From the view you could use <?php echo $post['User']['Profile']['firstname']; ?>