簡體   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