0

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?

1
  • did you mean the user id and the project sector id are all same in the three result?
    – Shoshi
    Jun 3, 2015 at 10:27

1 Answer 1

4

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);
2
  • Perfect, do I still need the distinct with groupby? or can I take that out? Jun 3, 2015 at 10:28
  • 2
    Group by does quite the same as distinct so no need for distinct
    – Szenis
    Jun 3, 2015 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.