Laravel order by hasmany relationship

隐身守侯 提交于 2019-12-01 01:33:18

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');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!