开发者

Add a friend feature in CakePHP

开发者 https://www.devze.com 2023-02-08 15:28 出处:网络
I need a simple add a friend feature in my application, through some research, I would need a jo开发者_开发技巧in table linking back to users table ? something like this: (I already have a users table

I need a simple add a friend feature in my application, through some research, I would need a jo开发者_开发技巧in table linking back to users table ? something like this: (I already have a users table)

Users-Friendships-Users

Can anyone give more details about this?


The friendships table should have following columns:

id Integer
user_from (the user who requested friendship)
user_to (the user who accepted friendship)
created (optional to track when your friendship started)

Then you need to create proper Model relation.

class User extends AppModel {
   ...
   var $hasMany = array(
      'UserFrom'=>array(
         'className'=>'Friendship',
         'foreignKey'=>'user_from'
      ),
      'UserTo'=>array(
         'className'=>'Friendship',
         'foreignKey'=>'user_to'
      )
   );
   var $hasAndBelongsToMany = array(
      'Friendship' => array(
          'className' => 'User',
          'joinTable' => 'friendships',
          'foreignKey' => 'user_from',
          'associationForeignKey' => 'user_to'
   );
   ...
}

class Friendship extends AppModel {
   ...
   var $belongsTo = array(
      'UserFrom'=>array(
         'className'=>'User',
         'foreignKey'=>'user_from'
      ),
      'UserTo'=>array(
         'className'=>'User',
         'foreignKey'=>'user_to'
      )
   )
   ...
}

This way you are defining 2 relation in each model. You can add HABTM relation too. Run bake script to build your controllers and views. Then in your code you can use something like this:

$this->User->UserFrom->find('all', 
    array(
        'conditions'=>array('user_from'=>1), 
        'contain'=>array('UserTo')
    )
);

This should return friends of user with ID 1 and all friends details.

Be careful with the recursive queries. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消