I have two eloquent models Threads
and Comments
, each thread hasMany comments.
While listing the threads, i need to order the threads by t
It's important to understand how Laravel's eager loading works. If we eager load your example, Laravel first fetches all threads. Then it fetches all comments and adds them to the threads object. Since separate queries are used, it isn't possible to order threads by comments.
You need to use a join instead. Note that I'm guessing at your table/column names in this example.
$threads = Thread::leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
Since you're joining, you might need to manually specify columns to select your tables column names.
$threads = Thread::select('thread.*')->leftJoin('comment', 'comment.thread_id', '=', 'thread.id')
->with('comments')
->orderBy('comment.created_at', 'desc')
->get();
public function profiles()
{
return $this->hasMany('Models\v1\Admin\UserProfile', 'user_id')->leftJoin('user_field', 'user_profile.user_field_id', '=', 'user_field.id')->orderBy('order');
}