简体   繁体   中英

Laravel how to get only one record per user

In my laravel -application, I want to display all users/candidates, which have taken an education. Now it might happen, that a user/candidate has taken more than one education, so in this case, just the latest education should be displayed.

I've come to this:

$users = User::whereHas('roles', function ($q) {
    $q->where('slug', 'candidate');
}
)->whereHas('educations')
 ->join('user_educations', 'user_educations.user_id', '=', 'users.id')
 ->join('educations', 'user_educations.education_id', '=', 'educations.id')
 ->join('education_levels', 'user_educations.education_level_id', '=', 'education_levels.id')
 ->select('users.id', 'users.name', 'users.surname', 'users.status', 'users.city', 'users.zipcode', 'users.birthday', 'users.avatar', 'educations.title as education', 'education_levels.title as education_level')
 ->where('user_educations.user_id', '=', 'users.id') // HERE IT FAILS - returns null
 ->first();

return response(['success' => true, "users" => $users], 200);

when I leave out the where('user_educations.user_id', '=', 'users.id') -clause, and do get() instead of first() , I get all users/candidates with educations, and also sometimes the same user multiple times, depending on how many educations he has taken.

how can I fix this?

The distinct method allows you to force the query to return distinct results, you can use it like this;

$users = DB::table('users')->groupBy('user_id')->distinct()->get();

If you want to take just the latest record, you should use "orderBy" to order your records, than pick a record with something like this :

$users = DB::table('users')->groupBy('user_id')->orderBy('created_at','desc')->distinct()->get();

You can look here for more detailed information about query builders in Laravel

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