Moritz
Moritz

Reputation: 177

CakePHP associations: how to retrieve all hasMany associations the proper way?

As a newbie to CakePHP I’m really struggling to understand how CakePHP’s associations (and basically the whole MVC) work, even after reading a lot of tutorials and documentation.

I have three models, layered as follows:

class User extends AppModel {
  public $hasMany = array('Album');
}

class Album extends AppModel {
  public $belongsTo = array('User');
  public $hasMany = array('Photo');
}

class Photo extends AppModel {
  public $belongsTo = array('Album');
}

I have a $user = $this->Auth->user() which seems more like an Array than an object. Although CakePHP seems really clever with automagically doing stuff for you, $user->getAlbums() and than a ->getPhotos(); on that object doesn’t seem to return anything. My question: how do I retrieve in a clever way the Albums of the authed user, and the Photos which are in an Album?

Upvotes: 0

Views: 68

Answers (1)

Justin T.
Justin T.

Reputation: 3701

There are several ways to achieve this.

how do I retrieve in a clever way the Albums of the authed user

Try this in your UsersController class :

$albums = $this->User->Album->findByUserId($this->Auth->user('id'));

...and the Photos which are in an Album?

As a benefit, queries by Cakephp get data from joined models... e.g :

debug($albums);


[0] => Array
        (
            [Album] => Array
                (
                    [id] => 1
                    [titre] => Premier Album
                    [contenu] => aaa
                    [created] => 2008-05-18 00:00:00
                )
            [Photo] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [album_id] => 1
                            [created] => 2008-05-18 00:00:00
                        )
                    [1] => Array
                        (
                            [id] => 2
                            [album_id] => 1
                            [created] => 2008-05-18 00:00:00
                        )
                )

However, if your resulting array grows too big, you should take a look at the great Containable Behavior

Upvotes: 1

Related Questions