Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent eager load Order by

I have problem with eloquent query. I am using eager loading (one to one Relationship) to get 'student' With the 'exam', Using the code below.

Student::with('exam')->orderBy('exam.result', 'DESC')->get() 

And i want to order received rows by the 'result' column in 'exam'. I am using

->orderBy('exam.result', 'DESC') 

But it is not working. Any ideas how to do it ?

like image 915
Andrius Avatar asked Sep 17 '13 22:09

Andrius


People also ask

How to order by in eager loading in Laravel?

If you want to order by an eager loaded relationship on-demand then you can pass in a function when defining the eager loading. The code will be like below. <? php User::with(['posts' => function ($query) { $query->orderByDesc('created_at'); }])->first();

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.

How does eager loading work?

At its core Eager Loading, is telling Eloquent that you want to grab a model with specific relationships that way the framework produces a more performant query to grab all the data you will need. By eager loading, you can take many queries down to just one or two.


2 Answers

Try this:

Student::with(array('exam' => function($query) {         $query->orderBy('result', 'DESC');     }))     ->get(); 
like image 60
Glad To Help Avatar answered Sep 19 '22 16:09

Glad To Help


If you need to order your students collection by the result column, you will need to join the tables.

Student::with('exam')        ->join('exam', 'students.id', '=', 'exam.student_id')        ->orderBy('exam.result', 'DESC')        ->get() 

In this case, assuming you have a column student_id and your exams table are named exam.

like image 25
Luis Dalmolin Avatar answered Sep 22 '22 16:09

Luis Dalmolin