Belal Khan
Belal Khan

Reputation: 148

Order by an array by key in laravel

I am using the below query to get the matched ID from the following tables where I will get only student_id.

With this student_id, I have to find the matched row from students table, and then I want to orderBy() the keys (e.g. name) from students table.

I make the relationship between student_mapping and student model.

$mapps = Student_mapping::select('student_id');

if($request->session_id) {
    $mapps = $mapps->where('session', '=', $request->session_id);
}
if($request->class_id) {
    $mapps = $mapps->where('class_id', '=', $request->class_id);

    if($request->group_id) {
        $mapps = $mapps->where('group_id', '=', $request->group_id);

        if($request->section_id) {
            $mapps = $mapps->where('section_id', '=', $request->section_id);
        }
    }
}

$mapps = $mapps->get();

$students = [];

foreach($mapps as $map) {
    if($map->student)
    {
        $students[] = Student::find($map->student_id);
    }
}

I have to make $students->orderBy('name', 'ASC'), But I can't do this.

Upvotes: 0

Views: 1356

Answers (3)

Jignesh Joisar
Jignesh Joisar

Reputation: 15165

$students = [];

foreach($mapps as $map) {
    if($map->student)
    {
        $students[] = Student::find($map->student_id);
    }
}

by laravel collection class see

return   collect($student)->sortBy('name')->values()->all();

Upvotes: 0

omitobi
omitobi

Reputation: 7334

You can use User::where('id', $map->student_id)->orderBy('name', 'ASC'); this doesn't look useful since id is unique anyway.

On a separate note, it looks like your code will suffer from multiple calls to the db.

You could simplify your query to be:

$student_ids = $mapps->pluck('student_id');
$students = Student::whereIn('id', $student_ids)->orderBy('name', 'ASC')->get();

PS: Eloquent (Model) wraps around QueryBuilder. See example of ordering or groupby in the documentation

Upvotes: 1

Jaime Rojas
Jaime Rojas

Reputation: 559

It'd be faster and better to get the query like this:

$students = Student::whereIn('id', $mapps)->orderBy('id')->get();

This would give you a Collection of all students which should be ordered by ID. If you want it as an array, remember calling the ->toArray() method on the collection, but it should serve its purpose as a collection either way.

Upvotes: 0

Related Questions