[英]Laravel Eloquent - Return unique values only and ignore all that appear more than once
I have 2 database tables.我有 2 个数据库表。
|---------------------|------------------|
| Users | Matches |
|---------------------|------------------|
| user_id | match_id |
|---------------------|------------------|
| user_1 |
|------------------|
| user_2 |
|------------------|
with user_1
and user_2
being user_id
s. user_1
和user_2
是user_id
。
I am now trying to retrieve all matches with unique values only.我现在正在尝试仅检索具有唯一值的所有匹配项。 As soon as a user ID is used twice, I don't want to retrieve ANY matches containing the id.一旦用户 ID 被使用两次,我就不想检索任何包含该 ID 的匹配项。
Example:例子:
MATCHES (match_id, user_1, user_2):匹配(match_id、user_1、user_2):
1, 1, 2
2, 1, 3
3, 4, 5
4, 6, 7
5, 7, 8
The query should return 3, 4, 5
ONLY, because it's the only match containing only unique user_ids.查询应仅返回3, 4, 5
,因为它是唯一只包含唯一 user_id 的匹配项。
How should I go about this?我应该如何 go 关于这个? I've been trying an approach using ->distinct()
but that doesn't work since it only removes duplicates but I want to kick other entries containing the values as well.我一直在尝试使用->distinct()
的方法,但这不起作用,因为它只删除重复项,但我也想踢出包含这些值的其他条目。
Simple and crude, not a query based solution, but will get you what you want.简单粗暴,不是基于查询的解决方案,但会得到你想要的。
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.