->orderBy('disciplineRelation.name') How i to do it?
$all = $sdc::with('studentRelation','disciplineRelation','classroomRelation')
->where('student',$request->id)
->orderBy('disciplineRelation.name')
->get();
Order by at query relation?
->orderBy('disciplineRelation.name')
You will need to JOIN the relation's table (table_name):
$all = $sdc::with('studentRelation','disciplineRelation','classroomRelation')
->join('table_name', 'sdc.foreign_key', 'table_name.primary_key')
->where('student',$request->id)
->orderBy('table_name.name')
->get();
You can do it like this ..
$all = $sdc::with('studentRelation', 'disciplineRelation', 'classroomRelation')
->where('student', $request->id)
->get()
->sortBy(function ($sdc) {
return $sdc->disciplineRelation->name;
});
@carcleo marks the thread as solved. Select the best answer you got.
@carcleo understand the difference between the the proposed solutions (i) uses the database to sort records in the Collection (ii) uses the Collection to sort the records. Depending on your data and schema, the database solution can be more efficient than sorting in PHP.
@Shivamyadav but it, ask for more memory
i like of to do the sort inside of query
anythink as
$all = $sdc::with('studentRelation', 'disciplineRelation', 'classroomRelation')
->where('student', $request->student)
->sortBy(function ($sdc) {
return $sdc->disciplineRelation->name;
})
->get();
A case should be
SELECT distinct(dc.id), dc.name
FROM
students_disciplines_classrooms sdc,
classrooms cl,
disciplines dc,
students st
where
sdc.student = st.id AND
sdc.classroom = cl.id AND
sdc.discipline = dc.id AND
sdc.student = 1
order by dc.name
but in eloquent way
@carcleo try with this
$all = $sdc::with(['disciplineRelation' => function($query) {
$query->select('id', 'name')->orderBy('name');
}])
->whereHas('studentRelation', function ($query) use ($request) {
$query->where('id', $request->student);
})
->get()
->unique('disciplineRelation.id')
->sortBy('disciplineRelation.name');
@Shivamyadav again, sorting in memory.
The best answer has already been given, use a join.
Please sign in or create an account to participate in this conversation.