user1806445
user1806445

Reputation: 67

Associations: HasMany with a BelogsTo inside it

Hi I am trying out CakePHP 2.5 and created the blog from the tutorial. I'm adding comments to blog posts, each comment has a user, but I can't seem to pull back the user information.

in my user model

public $hasMany = array(
    'Comment' => array(
        'className' => 'Comment',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ),
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'user_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

in my comments model

public $belongsTo = [
    'User' => [
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ],
    'Posts' => [
        'className' => 'Posts',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ]
];

and in the postmodel, post being whenre I want to display the comment and the username

public $belongsTo = [
    'User' => [
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ]
];

public $hasMany = [
    'Comment' => [
        'className' => 'Comment',
        'order'     => 'Comment.created DESC',
        'foreignKey'=> 'post_id'
    ]
];

viewing a post brings back the following comment information

  'Comment' => 
    array (size=1)
      0 => 
        array (size=6)
          'id' => string '1' (length=1)
          'content' => string 'This is a comment' (length=17)
          'created' => string '2015-10-23 15:59:55' (length=19)
          'modified' => string '2015-10-23 15:59:55' (length=19)
          'user_id' => string '1' (length=1)
          'post_id' => string '2' (length=1)

But this doesn't include the user information as I expected.

My question is how do I pull the user information for each comment within a post

Upvotes: 0

Views: 77

Answers (1)

bats-everywhere
bats-everywhere

Reputation: 67

Sorry, I don't have points for commenting. Could you post your find() method? Also, do you have recursion turned on, or is it off (turned to -1) and you are using contain to grab associated models?

Upvotes: 1

Related Questions