友情在CakePHP 2.x [英] Friendships in CakePHP 2.x

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

问题描述

我在设置与CakePHP 2的友谊时遇到问题。

I'm having trouble setting up friendships with CakePHP 2.

我有两个数据库表:用户 / strong>。我的用户表格包含以下列:

I have two database tables: users and friends. My users table has the following columns:


  • id

  • 电子邮件

  • 密码

我的朋友表有以下列:


  • id

  • user_id

  • friend_id


  • id
  • user_id
  • friend_id
  • approved

我有朋友在我的用户模型中设置为hasAndBelongsToMany关系:

I have friends set up as a hasAndBelongsToMany relationship in my Users model:

<?php
class User extends AppModel {
    public $hasAndBelongsToMany = array(
        'Friends' => array(
            'className' => 'User',
            'joinTable' => 'friends',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'friend_id',
            'unique' => true
        )
    );
}

现在,当我为用户尝试和检索朋友时,指定的用户发起,即 user_id 等于用户ID;它不会向我显示其他人可能已发起请求的位置(即当前用户的ID位于 friend_id 列中)。

Now, when I try and retrieve friends for a user, it only lists friendships that the specified user initiated, i.e. where user_id is equal to the user ID; it doesn't show me friends where the other person may have initiated the request (i.e. where the current user's ID is in the friend_id column).

如何获取朋友,因此 user_id friend_id 等于特定的ID?

How can I fetch friends, so records where either the user_id or friend_id column is equal to a particular ID?

推荐答案

我不认为你理解HABTM是如何工作的。阅读本书的这一部分。除了您为关系工作的表之外,您还需要一个friends_users表。我想如果你要这样设置,你需要定义一个友谊为拥有和属于许多用户。

I don't think you understand how HABTM works. Read this part of the book. You will need a friends_users table in addition to the tables you have for the relationship to work. I think if you were going to set it up this way, you'd need to define a Friendship as having and belonging to many Users.

但是,我怀疑是否你当前的设置你想要一个HABTM关系。它似乎是一个用户有多个朋友,就是这样。看看使用这种关系,它会给你相关的ID,如你所期望的。不要忘记定义朋友 belongsTo 用户。

However, I question whether with your current setup you want a HABTM relationship. It seems like a user hasMany friends, and that's it. Look into using that relationship, and it'll give you the relevant ID as you expect it to. Don't forget to define Friend belongsTo User.

这里是我的规范Cake 2.0友谊教程。我下载cakePHP 2.1,所以我有一个新的开始。我首先改变了我的安全盐和密码,然后添加了我的数据库连接。然后,我按如下所示构建数据库:

Here beings my canonical Cake 2.0 Friendship tutorial. I downloaded cakePHP 2.1 so I had a fresh start. I first changed my security salt and cipher, then added my database connection. Then I structured my database as follows:

数据库

users 表:

id         | int(11)
created    | datetime
username   | varchar(255)

/ p>

friendships table:

id         | int(11)
user_from  | varchar(255)
user_to    | varchar(255)
created    | datetime
status     | varchar(50)

显然,你的用户表可以/将有更多的东西,我需要。

Obviously, your users table can/will have more stuff, but this is the minimum I needed.

模型

好的,这是棘手的部分。这是我在用户模型中定义的关系。

Okay this is the tricky part. Here are the relationship I defined in my User model.

class User extends AppModel {
/* Other code if you have it */
        var $hasMany = array(
          'FriendFrom'=>array(
             'className'=>'Friendship',
             'foreignKey'=>'user_from'
          ),
          'FriendTo'=>array(
             'className'=>'Friendship',
             'foreignKey'=>'user_to'
          )
       );
       var $hasAndBelongsToMany = array(
          'UserFriendship' => array(
              'className' => 'User',
              'joinTable' => 'friendships',
              'foreignKey' => 'user_from',
              'associationForeignKey' => 'user_to'
            )
       );
/* Again, other code */
}

模型:

class Friendship extends AppModel {
/* Other code if you have it */
    var $belongsTo = array(
      'UserFrom'=>array(
         'className'=>'User',
         'foreignKey'=>'user_from'
      ),
      'UserTo'=>array(
         'className'=>'User',
         'foreignKey'=>'user_to'
      )
   );
/* Again, other code */
}

在模型上:友谊模式属于2个用户。用户模型有3个关联。在用户模型中的两个关系都是用于访问友谊模型数据的别名,所以我们可以使用 $ this-> User-> FriendTo $ this-> User-> FriendFrom 从控制器访问友谊模型。我第一次调用这些UserFrom和UserTo,镜像友谊模型的设置,但蛋糕提出了一个嬉皮士的相似之处,所以我不得不使他们更加鲜明。

Note on models: The friendship model belongs to 2 users. The user model has 3 associations. The two hasMany relationships in the User Model are both aliases for the accessing the Friendship model's data, so we can use $this->User->FriendTo or $this->User->FriendFrom from controllers to get to the Friendship model. I at first called these UserFrom and UserTo, mirroring the setup of the Friendship model, but Cake threw a hissyfit about similarities, so I had to make them more distinct.

控制器和数据视图
我使用烘焙工具烘焙控制器和视图。然后我创建了两个用户(丹尼尔和马丁),并创建了一个从丹尼尔到马丁的新友谊,状态为请求。然后我将友谊状态更新为已确认。

Controllers and Views: I baked controllers and views using the bake utility. I then created two users (Daniel and Martin) and created a new friendship from Daniel to Martin with a status of requested. I then updated the friendship status to confirmed.

我创建了以下无视自定义用户操作,来自UsersController的友谊:

I created the following viewless custom user action to demonstrate data retrieval about a friendship from the UsersController:

public function test() {
  $data = $this->User->FriendFrom->find('all', 
    array(
      'conditions'=>array('user_from'=>1), 
      'contain'=>array('UserTo')
    )
  );
  die(debug($data));
}



此查找使用UserModel的hasMany关系访问Friendship模型, ID为1的用户发起关系的关系的相关 user_from user_to 数据。

您的特定查找

Martin,在这个系统下,虽然你可以做不同的,你总是处理一个类似的方法,只要有两方面的关系。所有你需要做的是获取一个关系列表,其中您的用户ID是user1或user2(在我的情况下,只是因为我知道谁发起了关系,我有他们存储为user_to和user_from-我认为这是什么吓坏了你)。然后我遍历整个数组,选择相关的朋友数据,基于我是user1或2在给定的数组。这是一个很简单的方法,我只是把它放在我的用户模型。更改die(debug()); return $ friendslist 才能从控制器调用它并获取数组。

Martin, the find you're looking for is super simple under this system, and while you could do it differently, you'd always be dealing with a similar method, simply as long as there are always two sides to a relationship. All you have to do is get a list of relationships where your user ID is either user1 or user2 (in my case, just so I know who initiated the relationship, I have them stored as user_to and user_from- I think this is what intimidated you). Then I iterate through the whole array, selecting the relevant friend data based on whether I am user1 or 2 in that given array. It's a really simple method, and I just put it in my user Model. Change the die(debug()); to return $friendslist to be able to call it from your controller and get an array back.

public function getFriends($idToFind) {
  $data = $this->FriendFrom->find('all', 
    array(
      'conditions'=>array(
        'OR'=> array(
            array('user_to'=> $idToFind),
            array('user_from'=> $idToFind)
        )
        )
    )
  );
  $friendslist = array();
  foreach ($data as $i) {
    if ($i['FriendFrom']['user_from'] == $idToFind){
        $friendslist[] = $i['UserTo'];
    }
    elseif ($i['FriendFrom']['user_to'] == $idToFind){
        $friendslist[] = $i['UserFrom'];
    }
  }

  die(debug($friendslist));
}

这篇关于友情在CakePHP 2.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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