简体   繁体   中英

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?

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

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