Laravel order by hasmany relationship

China☆狼群 提交于 2019-11-30 20:33:17

问题


I have two eloquent models Threads and Comments , each thread hasMany comments.

While listing the threads, i need to order the threads by the created_at descending. So , i need to sort the threads using created at in Comments.

Apparently dot notation isn't helpful in ordering this way, how do i order the Threads correctly ?

$Threads= Thread::all()->orderBy("comment.created_at","desc")

回答1:


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();



回答2:


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');
}


来源:https://stackoverflow.com/questions/28634921/laravel-order-by-hasmany-relationship

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