I have a CakePHP app that allows users to be friends with other users. This is done using a HABTM relationship on the users table via a friends table for the join.
The friends table has: id, user_id, friend_id, and status fields.
And the model for the relationship looks like:
public $hasAndBelongsToMany = array(
'User'=>array(
'className' => 'User',
'joinTable' => 'friends',
'with' => 'Friend',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id'
)
);
So for example if I want to list the friends for the logged in user, I have the following:
$user = $this->User->find('first', array('conditions' => array('User.id' => $this->Auth->user('id'))));
$friends = $this->User->find('first',
array(
'conditions'=>array(
'User.id'=>$user['User']['id']
),
'contain'=>array(
'User'=>array(
'conditions'=>array(
'Friend.status'=>1
)
)
)
)
);
$this->set('friends', $friends);
Now the problem I have is when trying to show this list, getting the friend information!
If I do a debug on $friends I get:
array(
'User' => array(
'password' => '*****',
'id' => '6',
'username' => 'test',
'email' => '[email protected]',
'firstname' => 'Test',
'lastname' => 'User',
(int) 0 => array(
'password' => '*****',
'id' => '8',
'username' => 'johndoe',
'email' => '[email protected]',
'firstname' => 'John',
'lastname' => 'Doe',
'Friend' => array(
'id' => '1',
'user_id' => '6',
'friend_id' => '8',
'created' => '0000-00-00 00:00:00',
'status' => '1'
)
)
)
)
How do I show the list of friends then? As I have doing:
<?php foreach ($friends as $friend) : ?>
<li><?php echo $this->Html->link($friend['User']['firstname']. ' '. $friend['User']['lastname'], array('controller'=>'users','action'=>'view','userName'=>$friend['User']['username'])); ?></li>
<?php endforeach; ?>
But I just get: Undefined index: User [APP/View/Friends/index.ctp, line 44]
Any ideas what it is I'm doing wrong? I'm presuming it's something to do with the array not being properly used in the view.