Chris
Chris

Reputation: 805

List comments for picture with username cakePhp

I have a problem with my comments. I have User model:

public $hasMany = array('Photo','Comment');

Comment model:

public $belongsTo = array(
            'User'=>array(
                'className'=>'User',
                'foreignKey'=>'user_id'
            ),
            'Photo'=>array(
                'className'=>'Photo',
                'foreignKey'=>'photo_id'
            )
        );

and Photo Model

    public $belongsTo = array(
    'User'=>array(
        'className'=>'User',
        'foreignKey'=>'user_id'
    )
);

public $hasMany = array(
    'Comment'=>array(
        'className'=>'Comment',
        'foreignKey'=>'photo_id'
    )
);

When I read data of a photo I got:

'Photo' => array -> info about photo which is ok for me
'User' => array -> info about user ok for me
'Comment' => array -> all comments but only with id of users. 

How can I connet comments with users to get username related with comment while retrieving data about photo?

Upvotes: 0

Views: 688

Answers (1)

Nick Savage
Nick Savage

Reputation: 876

You need to call $this->recursive = 2 before you call find(), that will fetch all associations of every object returned by your query. Alternatively you can set the $recursive variable inside any of your models.

The different types of recursion are as follows:

  • -1 Cake fetches Photo data only, no joins.
  • 0 Cake fetches Photo data and its domain
  • 1 Cake fetches a Photo, its domain and its associated Comments
  • 2 Cake fetches a Photo, its domain, its associated Comments, and the Comments’ associated Users

I also suggest considering Containable since you have complete control of all the data that is returned, down to specifying each field in any association

The photo model:

<?php
class Photo extends AppModel {
    public $actsAs = array('Containable');
}

And your find method will look like this:

<?php
$this->Photo->find('all', array(
    'contain' => array(
        'User',
        'Comment' => array(
            'User' = array(
                'fields' => array('username')
            ),
            'conditions' => array(
                'Comment.erased' => 0
            )
        ))
    'conditions' => array(
        'Photo.id' => $id
)));

Upvotes: 4

Related Questions