In my application I have users that are able to be friends with other users.
This is controlled with a users table and a friends_users table.
The friends_users table has the following columns: id, user_id, friend_id, status
And the model User looks like:
public $hasAndBelongsToMany = array(
'Friend'=>array(
'className' => 'User',
'joinTable' => 'friends_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id'
)
);
This seems to work fine when viewing the Users for a user who is in the user_id column, but doesn't work the other way around, i.e. in reverse... Any ideas why?
Here is the method I use to list the friends for a user:
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $this->Auth->user('id')),
'contain'=>'Profile'
));
$friends = $this->User->find('first',
array(
'conditions'=>array(
'User.id'=>$user['User']['id']
),
'contain'=>array(
'Profile',
'Friend'=>array(
'Profile',
'conditions'=>array(
'FriendsUser.status'=>1
)
)
)
)
);
$this->set('friends', $friends);