繁体   English   中英

Laravel 如何让每个用户只获取一条记录

[英]Laravel how to get only one record per user

在我的laravel ,我想显示所有接受过教育的用户/候选人。 现在可能会发生,用户/候选人接受了不止一种教育,因此在这种情况下,应该只显示最新的教育。

我来到了这个:

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

当我省略where('user_educations.user_id', '=', 'users.id')并使用get()而不是first() ,我会得到所有受过教育的用户/候选人,有时还有同一个用户多次,取决于他接受了多少教育。

我怎样才能解决这个问题?

distinct 方法允许您强制查询返回不同的结果,您可以像这样使用它;

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

如果你只想获取最新的记录,你应该使用“orderBy”来排序你的记录,而不是选择一个像这样的记录:

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

您可以在此处查看有关 Laravel 中查询构建器的更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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