在 CakePHP 中添加好友功能 [英] Add a friend feature in CakePHP

查看:39
本文介绍了在 CakePHP 中添加好友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的应用程序中添加一个简单的朋友功能,通过一些研究,我需要一个连接表链接回用户表?像这样:(我已经有一个用户表)

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)

用户-友谊-用户

谁能提供更多有关此的详细信息?

Can anyone give more details about this?

推荐答案

Friends 表应该有以下列:

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'
      )
   )
   ...
}

通过这种方式,您可以在每个模型中定义 2 个关系.您也可以添加 HABTM 关系.运行烘焙脚本来构建您的控制器和视图.然后在你的代码中你可以使用这样的东西:

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')
    )
);

这应该返回 ID 为 1 的用户的朋友和所有朋友的详细信息.

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

小心递归查询.:)

这篇关于在 CakePHP 中添加好友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆