简体   繁体   中英

Laravel Eloquent - Return unique values only and ignore all that appear more than once

I have 2 database tables.

|---------------------|------------------|
|      Users          |     Matches      |
|---------------------|------------------|
|     user_id         |     match_id     |
|---------------------|------------------|
                      |     user_1       |
                      |------------------|
                      |     user_2       |
                      |------------------|

with user_1 and user_2 being user_id s.

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.

Example:

MATCHES (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.

How should I go about this? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM