[英]Laravel Eloquent - Return unique values only and ignore all that appear more than once
我有 2 个数据库表。
|---------------------|------------------|
| Users | Matches |
|---------------------|------------------|
| user_id | match_id |
|---------------------|------------------|
| user_1 |
|------------------|
| user_2 |
|------------------|
user_1
和user_2
是user_id
。
我现在正在尝试仅检索具有唯一值的所有匹配项。 一旦用户 ID 被使用两次,我就不想检索任何包含该 ID 的匹配项。
例子:
匹配(match_id、user_1、user_2):
1, 1, 2
2, 1, 3
3, 4, 5
4, 6, 7
5, 7, 8
查询应仅返回3, 4, 5
,因为它是唯一只包含唯一 user_id 的匹配项。
我应该如何 go 关于这个? 我一直在尝试使用->distinct()
的方法,但这不起作用,因为它只删除重复项,但我也想踢出包含这些值的其他条目。
简单粗暴,不是基于查询的解决方案,但会得到你想要的。
public function strictlyUniqueMatches()
{
$matches = Matches::distinct()->get();
$present = [];
foreach ($matches as $idx => $match) {
if (!isset($present[$match->user_1])) {
$present[$match->user_1] = 0;
}
if (!isset($present[$match->user_2])) {
$present[$match->user_2] = 0;
}
$present[$match->user_1]++;
$present[$match->user_2]++;
}
return $matches->filter(function ($match) use ($present) {
if ($present[$match->user_1] > 1) {
return false;
}
if ($present[$match->user_2] > 1) {
return false;
}
return true;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.