Users::class
进行内连接,但失败了。最好能够运行两个查询并查看是否存在重叠部分。因此,一个人已经联系了另一个人,反之亦然。friends | users
----------|------
send_id | id
receive_id| name
is_blocked|
样例数据及期望结果
users.id | name
---------|------
1 | foo
2 | bar
3 | baz
friends
send_id | receive_id | is_blocked
--------|------------|-----------
1 | 2 | 0
2 | 1 | 0
1 | 3 | 0
3 | 1 | 1
2 | 3 | 0
用户应该有一个名为“朋友”的清晰关系。它应该是你从“requestedFriends”或“receivedFriends”中期望的内容。
foo->friends
returns `baz`
bar->friends
returns `foo`
baz->friends
returns empty collection
目前正在使用
// User.php
public function requestedFriends()
{
$left = $this->belongsToMany(User::class, 'friends','send_id','receive_id')
->withPivot('is_blocked')
->wherePivot('is_blocked','=', 0)
->withTimestamps();
return $left;
}
public function receivedFriends()
{
$right = $this->belongsToMany(User::class, 'friends','receive_id','send_id')
->withPivot('is_blocked')
->wherePivot('is_blocked','=', 0)
->withTimestamps();
return $right;
}
public function friends()
{
$reqFriends = $this->requestedFriends()->get();
$recFriends = $this->receivedFriends()->get();
$req = explode(",",$recFriends->implode('id', ', '));
$intersect = $reqFriends->whereIn('id', $req);
return $intersect;
}
目前的研究
Laravel多对多自引用表只能单向工作 -> 老问题,但仍然相关。
https://github.com/laravel/framework/issues/441#issuecomment-14213883 -> 是的,它可以工作...但是只有单向。
https://laravel.com/docs/5.8/collections#method-wherein 目前我发现在eloquent中这是唯一的方法。
https://laravel.com/docs/5.7/queries#joins -> 理想情况下,我会找到一个使用内连接到自身的解决方案,但无论我怎样放置ID,都无法让解决方案起作用。
一个解决方案应该
一个解决方案应该在laravel 5.7或5.8中使用eloquent来内连接自引用表,只有在friends表中多个行中存在send_id
和receive_id
时才存在关系。
或者
以某种方式让社区知道这是做不到的。
谢谢您的帮助!