Laravel order by hasmany relationship

前端 未结 2 913
小蘑菇
小蘑菇 2021-01-07 08:02

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

While listing the threads, i need to order the threads by t

相关标签:
2条回答
  • 2021-01-07 08:16

    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();
    
    0 讨论(0)
  • 2021-01-07 08:20
    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');
    }
    
    0 讨论(0)
提交回复
热议问题