Laravel Sort By Relation Column Hello Mates, Here I want to sort by the relationship column updated_at column. I was doing like this but getting an error. any help would be great. TIA
$students = User::select([
'id',
'first_name',
'last_name',
'email',
'active',
'department_id'
])
->where('department_id', 5)
->where('active', 'yes')
->withCount('subjects')
->with(['subjects' => function ($q){
$q->orderBy('updated_at', 'DESC');
}])
->orderBy('subjects.updated_at', 'DESC')
->get();
$students = User::select([
'id',
'first_name',
'last_name',
'email',
'active',
'department_id'
])
->join('subjects', 'subjects.user_id', '=', 'users.id')
->where('department_id', 5)
->where('active', 'yes')
->withCount('subjects')
->orderByDesc('subjects.updated_at')
->get();
@bugsysha In this case I'm not getting the subjects object in response. I wanna that object in response too
Just add with(['subjects']) to the query.
$students = User::select([
'id',
'first_name',
'last_name',
'email',
'active',
'department_id'
])
->join('subjects', 'subjects.user_id', '=', 'users.id')
->where('department_id', 5)
->where('active', 'yes')
->with('subjects')
->withCount('subjects')
->orderByDesc('subjects.updated_at')
->get();
@bugsysha No luck. it is still empty and also I wanna sort the results by the updated_at column inside the subjects object.
->with(['subjects' => function ($q){
$q->orderBy('updated_at', 'DESC');
}])
How about changing the orderBy() to orderByRaw('subjects.updated_at DESC')?
$students = User::select([
'id',
'first_name',
'last_name',
'email',
'active',
'department_id'
])
->where('department_id', 5)
->where('active', 'yes')
->withCount('subjects')
->with(['subjects' => function ($q){
$q->orderBy('updated_at', 'DESC');
}])
->orderByRaw('subjects.updated_at DESC')
->get();
@ep !sode getting an error like this
SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "subjects"
@deepu07 orderByDesc('subjects.updated_at') sorts them by subjects updated_at column. with('subjects') should give you subjects.
@bugsysha if I use `with('subjects') getting this err
SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "subjects"
but instead of with if do join it is working but that join is giving duplicate records in results
@deepu07 Please check
Laracast:
Stackoverflow:
@deepu07
but instead of with if do join it is working but that join is giving duplicate records in results
I don't have your database to see what is going on. You need to check that on your own. What you can do is see what exact query is being executed and work on that. So instead of ->get() at the end, you can replace it toSql() and see the query which is generated. Paste that into your database client and tweak it to your liking and then just make adjustments to Eloquent statement.
Please sign in or create an account to participate in this conversation.