加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel ORM友谊关系,无重复

发布时间:2020-12-14 19:48:24 所属栏目:大数据 来源:网络整理
导读:用雄辩的方式塑造友谊关系的最佳方式是什么?我的表模式在下面,我想定义一个关系,我可以检索所有的朋友,如下所示. ?phpclass User extends Eloquent {public function friends() { return $this-belongsToMany('User','friendships','user_id','friend_id')-
用雄辩的方式塑造友谊关系的最佳方式是什么?我的表模式在下面,我想定义一个关系,我可以检索所有的朋友,如下所示.
<?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 |
+----+---------+-----------+----------+---------------------+---------------------+

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

友谊表

user_id:请求友谊的用户ID
friend_id:目标朋友的用户ID
州:友谊是否正在等待,接受或阻止.
created_at和updated_at

我知道有一些解决方案来自Laravel Many to many self referencing table only works one way,我可以从关系的两边检索朋友,但我必须是两行,例如,如果用户1和3是朋友,那么在一行user_id = 3和friend_id = 1,在下一行反之亦然. (或者,如果我没有两行,我必须进行两次查询).

您不应该尝试将两行应该转换成一行,但如果您要尝试这样做,那么您绝对不需要两次访问数据库:
select * from users where (user_id = :user_id and friend_id = :friend_id) or  (friend_id = :friend_id and user_id = :user_id)

在Laravel中将是:

Users::whereRaw('(user_id = ? and friend_id = ?) or (friend_id = ? and user_id = ?)',[            
    $user_id,$friend_id,$user_id
]);

你也可以做分组来分组,但这有点复杂.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读