Axiol
Axiol

Reputation: 5962

Getting some extra information from a comment

So, I have a basic members system with CakePHP. They can post stuff and I'ld like to add a comment system.

So I made the table in the DB and made the models and the users / posts / comments are linked this way :

Users model :

public $hasMany = array("Post", "Comment");

Posts model :

public $belongsTo = "User";
public $hasMany = "Comment";

Comments model :

public $belongsTo = array("User", "Post");

And it seems to work pretty well, I correctly get the comment for a post, here the debug for a post :

array(
    'Post' => array(
        'id' => '25',
        'title' => 'Rocket Club',
        'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam elementum sem ac sem imperdiet cursus. Quisque venenatis pulvinar ornare. Donec rutrum, lacus vel imperdiet sagittis, metus risus interdum ante, iaculis venenatis arcu nibh et odio.',
        'image' => '25-75da9db5.jpg',
        'created' => '2012-09-07 01:40:14',
        'user_id' => '19'
    ),
    'User' => array(
        'password' => '*****',
        'id' => '19',
        'username' => 'Axiol',
        'mail' => '*****',
        'firstname' => 'Arnaud',
        'lastname' => 'Delante',
        'description' => 'C'est moi le monsieur qui est derrière ce site. Dingue hein ?',
        'local' => '4420 Saint-Nicolas, Belgique',
        'twitter' => 'Axiol',
        'facebook' => 'axiol',
        'gplus' => '100906827397700671747',
        'github' => 'Axiol',
        'website' => 'http://www.axioland.me',
        'created' => '2012-09-04 02:10:31',
        'lastlogin' => '2012-09-07 01:38:44',
        'active' => '1'
    ),
    'Comment' => array(
        (int) 0 => array(
            'id' => '1',
            'content' => 'Test test d'un joli commentaire constructif et tout pour aider la personne qui a postée l'image.',
            'post_id' => '25',
            'user_id' => '19'
        )
    )
)

But, I'ld like more. I'ld to know if there is an easy way to have some extra informations about the user that made the comment (like his nickname and his mail) ? Is there a build in way ?

Upvotes: 0

Views: 70

Answers (1)

Choma
Choma

Reputation: 708

There are two ways to do it.

1- set 'recursive' => 2 in your find() call. The problem with this approach is that it will bring all the data from the second level associations, which may be too much.

2- Use Containable behavior, and try something like this:

$this->Post->find('first', array('conditions' => array('Post.id' => 1), 'contain' => array('User', 'Comment', 'Comment.User')));

Upvotes: 2

Related Questions