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

Php Laravel如何为每个用户只获取一条记录,php,laravel,Php,Laravel,在我的laravel-应用程序中,我想显示所有接受过教育的用户/候选人。现在可能会出现这样的情况,即用户/候选人接受了不止一种教育,因此在这种情况下,只应显示最新的教育 我想到这一点: $users = User::whereHas('roles', function ($q) { $q->where('slug', 'candidate'); } )->whereHas('educations') ->join('user_educations', 'user_ed

在我的
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\u educations.user\u 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中查找有关查询生成器的更详细信息

您使用的是什么版本的Laravel?@Rwd Laravel 5.8我不确定您为什么想要最后一个
位置(失败的一个),因为
加入('user_educations',…)
将为您解决这个问题。另外,仅供参考,如果您想添加一个
where
子句来比较两列,您可以使用
whereColumn
。至于只获取最新的教育,您始终可以在您的
用户
模型上创建一个
hasOne
关系,以获取最新的
教育