Add a friend feature in CakePHP

元气小坏坏 提交于 2019-11-30 20:33:38

问题


I need a simple add a friend feature in my application, through some research, I would need a join 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?


回答1:


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. :)



来源:https://stackoverflow.com/questions/4911812/add-a-friend-feature-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!