hasAndBelongsToMany only working one way
Posted
by
Cameron
on Stack Overflow
See other posts from Stack Overflow
or by Cameron
Published on 2012-09-26T21:21:43Z
Indexed on
2012/09/26
21:37 UTC
Read the original article
Hit count: 208
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);
© Stack Overflow or respective owner