Chris Townsend
Chris Townsend

Reputation: 2716

DISTINCT method using Laravel 5 eloquent query builder

I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query

//Get users that are part of this sector

        $users = DB::table('users')->distinct()
                            ->join('projects', 'users.id', '=', 'projects.userID')
                            ->where('projects.sectorID', '=', $sector->sectorID)
                            ->get();
        dd($users);

The result shows 3 users with the same ID, when I only want one of them in the results.

How should I change my query?

Upvotes: 0

Views: 3659

Answers (1)

Szenis
Szenis

Reputation: 4170

Try to use group by id

$users = DB::table('users')
     ->join('projects', 'users.id', '=', 'projects.userID')
     ->where('projects.sectorID', '=', $sector->sectorID)
     ->groupBy('users.id')
     ->get();

dd($users);

Upvotes: 4

Related Questions