Eloquent eager load Order by

Andrius picture Andrius · Sep 18, 2013 · Viewed 53.3k times · Source

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 ?

Answer

Glad To Help picture Glad To Help · Sep 18, 2013

Try this:

Student::with(array('exam' => function($query) {
        $query->orderBy('result', 'DESC');
    }))
    ->get();