Add a friend feature in CakePHP

前端 未结 1 1771
甜味超标
甜味超标 2021-01-07 10:19

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

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 10:30

    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 讨论(0)
提交回复
热议问题