gpt4 book ai didi

php - 没有重复的 Laravel ORM 友谊关系

转载 作者:可可西里 更新时间:2023-11-01 12:35:36 26 4
gpt4 key购买 nike

用 Eloquent 方式建立友谊关系的最佳方式是什么?我的表架构如下,我想定义一种关系,我可以在其中检索所有 friend ,如下所示。

<?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 的 friend 时,上面的关系接近工作 我得到用户 1 和 3 但显然我想要 1 和 2。

友谊表

user_id: 请求好友的用户id
friend_id: 目标好友的User Id
state: 友谊是未决、接受还是阻止。
created_at 和 updated_at

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

最佳答案

您可以进行两次查找,and use a union query ,因此只访问数据库一次。将所有这些放在自定义函数中:

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

关于php - 没有重复的 Laravel ORM 友谊关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com