簡體   English   中英

Laravel Eloquent - 僅返回唯一值並忽略所有多次出現的值

[英]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_1user_2user_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM