Laravel ORM友谊关系没有重复

Tho*_*son 8 php orm laravel laravel-4

用雄辩的方式塑造友谊关系的最佳方式是什么?我的表架构在下面,我想定义一个关系,我可以检索所有的朋友,如下所示.

<?php

class User extends Eloquent {

public function friends() {
    return $this->belongsToMany('User', 'friendships', 'user_id', 'friend_id')->orWhere($this->id,'=', 'friend_id');
  }
}

+----+---------+-----------+----------+---------------------+---------------------+
| id | user_id | friend_id | state    | created_at          | updated_at          |
+----+---------+-----------+----------+---------------------+---------------------+
|  1 |       3 |         1 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
|  2 |       2 |         3 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
+----+---------+-----------+----------+---------------------+---------------------+
Run Code Online (Sandbox Code Playgroud)

当我寻找用户ID为3的朋友时,上面的关系接近工作我得到了用户1和3,但显然我想要1和2.

友谊表

user_id:请求友情
friend_id的用户ID:目标朋友
状态的用户ID :友谊是待处理,被接受还是被阻止.
created_at和updated_at

我知道有很多来自Laravel的解决方案许多自我引用表只能以一种方式工作,我可以从关系的两边检索朋友,但我必须是两行,例如,如果用户1和3是朋友,那么在一行user_id = 3,friend_id = 1,在下一行反之亦然.(或者,如果我没有两行,我必须进行两次查询).

Lau*_*nce 6

您可以执行两次查找,并使用联合查询,因此只能访问数据库一次.将所有这些放在自定义函数中:

class User extends Eloquent {

  public function friends()
  {
     $first = $this->belongsToMany('User', 'friendships', 'user_id', 'friend_id');  
     return $this->belongsToMany('User', 'friendships', 'friend_id', 'user_id')->union($first);  
  }
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*eon 4

您不应该尝试将两行变成一行,但如果您要尝试这样做,那么您绝对不需要两次访问数据库:

select * from users where (user_id = :user_id and friend_id = :friend_id) or  (friend_id = :friend_id and user_id = :user_id)
Run Code Online (Sandbox Code Playgroud)

在 Laravel 中是:

Users::whereRaw('(user_id = ? and friend_id = ?) or (friend_id = ? and user_id = ?)', [            
    $user_id,
    $friend_id,
    $friend_id,
    $user_id
]);
Run Code Online (Sandbox Code Playgroud)

您也可以使用 sub-wheres 将它们分组,但这有点复杂。