carcleo's avatar

->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')

0 likes
8 replies
tykus's avatar

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();
1 like
Shivamyadav's avatar

You can do it like this ..

$all = $sdc::with('studentRelation', 'disciplineRelation', 'classroomRelation')
    ->where('student', $request->id)
    ->get()
    ->sortBy(function ($sdc) {
        return $sdc->disciplineRelation->name;
    });
tykus's avatar

@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.

carcleo's avatar

@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

Shivamyadav's avatar

@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');
Snapey's avatar

@Shivamyadav again, sorting in memory.

The best answer has already been given, use a join.

Please or to participate in this conversation.