0

another fairly basic question I suppose, but I feel like I'm running in circles and out of ideas, haha.

I'm trying to create a commenting system with pagination (via Ajax), which has to be able to display the name, avatar, etc. of the user that wrote a particular comment. Sounds simple enough, right?

Well, everything works fine, except so far I simply wasn't able to find a way to retrieve the corresponding users information and I couldn't find anything helpful in the docs either.

Here's my pagination code so far:

$this->paginate['Comment'] = array(
    'conditions'=>array('Entry.id'=>$id),
    'contain' => array('Entry', 'User'=>array('avatar', 'username') ),
    'limit' => 10
);
$comments = $this->paginate('Comment');
$this->set(compact('comments'));

So I've used contain to get the data of the user model, which I try to display in my view like this:

echo $comment['User']['username'];
echo $comment['User']['avatar'];

But that way, it of course displays the information of the user corresponding to $id...

However, I need to get a users info through the foreignkey user_id of the current comment. And at the moment I'm at a loss how to do that... Any help would be greatly appreciated. Thanks in advance!

John Bachir
  • 22,495
  • 29
  • 154
  • 227
  • you can use pr($comment) to debug your results. anyway, why not leaving the User complete (no avatar/username filter)? does this work? – mark Oct 23 '11 at 12:30
  • Thank you for the tip Mark! Well, thing is, the app works perfectly fine in that it fetches the User information through the $id of the current page. I.e. if I'm on the entry page 10, all comments that are added will have the user information from the user with id 10, haha... So to remedy that I need it to get the user info not through the $id but a find operation which gets the data of the user that actually wrote the comment. It's just that within the pagination context, I have no idea how to achieve that... – AliTheBandit Oct 23 '11 at 12:45

2 Answers2

0

if I remember correctly

'contain' => array('Entry', 'User.avatar,User.username')),

should do the trick

mark
  • 21,691
  • 3
  • 49
  • 71
  • Thank you, but unfortunately that didn't make a change... It keeps retrieving the user info via the $id rather than the foreign key user_id... – AliTheBandit Oct 23 '11 at 13:01
0

Okay, I solved it...

I just had to add the proper foreignKey to my Comment model, i.e:

var $belongsTo = array(
'Entry' => array('className' => 'Entry', 'foreignKey' => 'page_id'),
'User' => array('className' => 'User', 'foreignKey' => 'user_id'),
);

Now it finally fetches the appropriate user information!

  • strange. usually "user_id" as default foreign key should work without explicitly stating it... – mark Oct 23 '11 at 17:14