I want to group by an laravel eloquent with two classes come in with() I want to add column of these two with classes in group by
$query = CourseEnrolled::with('user', 'course')->latest()->groupBy('course_id','user_id')
Here course id come from course table and user id come from user table. it successfully group columns but does sort latest record. It display old record only
I have also tried but still same result
$query = CourseEnrolled::with('user', 'course')->orderBy('created_at')->groupBy('course_id','user_id')
CodePudding user response:
u cant query them directly with the eloquent model of CourseEnrolled
. if you want to add additional queries with other models, you have to use with() in this way :
CourseEnrolled::with('user' , function($user){
// now u can use any query with user fields
$user->where('user-name' , 'value');
})
CodePudding user response:
This query solve my problem
$query = CourseEnrolled::with('user', 'course')->latest()->whereIn('id', function($q){
$q->select(DB::raw('MAX(id) FROM course_enrolleds GROUP BY user_id,course_id'));
});