carcleo's avatar

To do a orderBy

how i can to do this sortBy() inside of query without alter the result?

$sdc::with('studentRelation', 'disciplineRelation', 'classroomRelation')
    ->where('student', $request->student)
    ->get()
    ->sortBy(function ($sdc) {
        return $sdc->disciplineRelation->name;
});
0 likes
5 replies
Shivamyadav's avatar

Try 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'); 
Jsanwo64's avatar

Try @shivamyadav suggestion or this

$all = Sdc::with(['disciplineRelation:id,name'])
    ->whereHas('studentRelation', function ($query) use ($request) {
        $query->where('id', $request->student);
    })
    ->join('disciplines', 'sdcs.discipline_id', '=', 'disciplines.id')
    ->orderBy('disciplines.name') // Sort directly by discipline name
    ->distinct('disciplines.id') // Ensure uniqueness at the database level
    ->select('sdcs.*') // Select only columns from the main table
    ->get();
1 like
Tray2's avatar

You should let the database do the sorting like @jsanwo64 shows, it's both faster and uses less resources that sorting a collection in php, just make sure that you have an index on the name column.

However, try not to use distinct in your query if you can avoid it, it generally slows the query down.

Tray2's avatar

@carcleo There is nothing wrong with using distinct if you need to, but if you can avoind it, it's better.

The distinct query looks at more records, and filters out any and all duplicates, causing a probable full table scan, which is not good.

Please or to participate in this conversation.