In my app I have three tables:
Users
Profiles
Friends
The User has one Profile and Profiles have one User and have many Friends. Friends have many Profiles.
In the Profile model I have a method that gets a list of Profiles for a Profile (BUT it uses the related username which comes from the user table.)
public function getFriends($username) {
return $this->find('all', array(
'conditions' => array(
'User.username' => $username,
'Friend.status' => 1
)
));
}
So it should be getting a list of profiles that match where the username matches a User and Friend status is 1. How do I do this though?
I’ll also post my associations so you can understand the DB:
User Model:
public $hasOne = 'Profile';
Profile Model:
public $belongsTo = 'User';
public $hasMany = array(
'ProfileFrom'=>array(
'className'=>'Friend',
'foreignKey'=>'profile_from'
),
'ProfileTo'=>array(
'className'=>'Friend',
'foreignKey'=>'profile_to'
)
);
public $hasAndBelongsToMany = array(
'Friendship' => array(
'className' => 'Profile',
'joinTable' => 'friends',
'foreignKey' => 'profile_from',
'associationForeignKey' => 'profile_to'
)
);
public $actsAs = array('Containable');
Friend Model:
public $belongsTo = array(
'UserFrom'=>array(
'className'=>'Profile',
'foreignKey'=>'profile_from'
),
'UserTo'=>array(
'className'=>'Profile',
'foreignKey'=>'profile_to'
)
);
public $actsAs = array('Containable');
This looks complicated, I’d suggest having a look at Containable (a core cakephp behavior) which makes selecting which data to fetch a lot easier (especially with regards to preventing selecting too much data). Please consider using that for your whole app.
It seems you’re trying to tell cake to search in associated Friend model, but if I’m right the only associations existing to the friend are aliased as ProfileTo and ProfileFrom. So I’m guessing cake won’t know where to fiend ‘Friend’. But in the future it would be helpful to post any errors as well.
See my suggestion below for a possible fix.
For now you could do the following:
In ProfileModel:
It should work like this. So in FriendsController you should now be able to do
$this->Friend->UserTo->getFriends('cameron');That should fetch the profile belonging to the user with username ‘cameron’, and all Friends associated with this profile.
There’s one small thing still bothering me though, and that’s the fact that you got an error stating that ProfileTo isn’t associated with Profile, which is weird as in your example that relation is obviously defined.
The cause might be a fault in the definition of your associations, but I’m not sure.
One more suggestion, if the above code doesn’t work, replace the
containarray with: