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 ?
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();
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.
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.
Try this:
Student::with(array('exam' => function($query) { $query->orderBy('result', 'DESC'); })) ->get();
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With