Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: How to order results of related models?

I have a model called School and it has many Students .

Here is the code in my model:

public function students() {     return $this->hasMany('Student'); } 

I am getting all the students with this code in my controller:

$school = School::find($schoolId); 

and in the view:

@foreach ($school->students as $student) 

Now I want to order the Students by some field in the students table. How can I do that?

like image 502
Debiprasad Avatar asked Sep 06 '14 12:09

Debiprasad


People also ask

How do you use order by in eloquent?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.

Is Laravel eloquent slow?

Laracasts Veteran Sure it is slow, first it fetch all the record in one time, then it instantiate an eloquent object for each lines. It is not made to retrieve 10 000 objects.

What is orderBy in Laravel?

The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order. By Ascending Order: $users = DB::table('users')->orderBy('name', 'asc')->get();


2 Answers

You have a few ways of achieving this:

// when eager loading $school = School::with(['students' => function ($q) {   $q->orderBy('whateverField', 'asc/desc'); }])->find($schoolId);  // when lazy loading $school = School::find($schoolId); $school->load(['students' => function ($q) {   $q->orderBy('whateverField', 'asc/desc'); }]);  // or on the collection $school = School::find($schoolId); // asc $school->students->sortBy('whateverProperty'); // desc $school->students->sortByDesc('whateverProperty');   // or querying students directly $students = Student::whereHas('school', function ($q) use ($schoolId) {   $q->where('id', $schoolId); })->orderBy('whateverField')->get(); 
like image 135
Jarek Tkaczyk Avatar answered Oct 22 '22 13:10

Jarek Tkaczyk


you can add orderBy to your relation, so the only thing you need to change is

public function students() {     return $this->hasMany('Student'); } 

to

public function students() {     return $this->hasMany('Student')->orderBy('id', 'desc'); } 
like image 43
fico7489 Avatar answered Oct 22 '22 12:10

fico7489