tags:

views:

269

answers:

3

Is there a shortcut for creating Unary associations in Cake?

For example, a user is a friend of another user. I'm pretty sure it's going to violate cake's conventions if I try it the hard way and code the associations myself.

Cake has HABTM:

var $hasAndBelongsToMany = array(
 'User' =>
  array(
   'className' => 'User',
   'joinTable' => 'friends',
   'foreignKey' => 'user_id',
   'associationForeignKey' => 'friend_id',
   'unique' => true
  )
);

Will this work? A user model assoc to another user model.

Update: How do I save the data now?

$this->data["Friend"] = $request["Requester"];
$this->data["Admirer"] = $request["Requestee"];       
$this->Friend->create();
$this->Friend->save($this->data);

$request["Requester"] and $request["Requestee"] both hold objects of type User. The HABTM rel is defined in the User model

var $hasAndBelongsToMany = array(
     'Friend' => array(
      'className' => 'Friend',
      'joinTable' => 'friends',
      'foreignKey' => 'user_id',
      'associationForeignKey' => 'id'
     ),
     'Admirer'=>array(
            'className'=>'Friend',
            'joinTable'=>'friends',
      'foreignKey' => 'friend_id',
            'associationForeignKey' => 'id',            
        )
    );

All that happens is the $data->["Friend"]'s id is stored in the id column of the friends table

A: 

Hi!

In CakePHP there are several variables in your model available to do that, like $hasMany, $belongsTo and $hasAndBelongsToMany. Please read the Cookbook for further explaination.. http://book.cakephp.org/view/78/Associations-Linking-Models-Together .

In your example, I think you need HABTM.

Bjorn
It's not really helpful just sending him to read all the models. He obviously already did.
Eduardo Romero
+1  A: 

Bjorn,

he is asking about User habtm User...

your join table should be users_users and the relation should look like this

    var $hasAndBelongsToMany = array(
        'Friend' =>
                array(
                        'className' => 'UserUser',
                        'joinTable' => 'users_users',
                        'foreignKey' => 'user_id',
                        'associationForeignKey' => 'friend_id',
                        'unique' => true
                )
);

i think that should do the trick

dogmatic69
and 'Friend' has a separate model and controller than User?
zero juan
The join table doesn't *have* to be called users_users, but if you want to use Cake's automagic, then it should be.
Matt Huggins
Also, the className value should just be "User" if that's the name of your Model. You can define a join table if you like via: 'with' => 'UsersUser', but that's only necessary if there's additional HABTM data on the join table.
Matt Huggins
+3  A: 
TehTreag
To match the singular model name format, I would recommend using 'Friend' instead of 'Friends', and 'Admirer' instead of 'Admirers'. Other than that, this is a good approach.
Matt Huggins