简体   繁体   English

Laravel通过hasmany关系排序

[英]Laravel order by hasmany relationship

I have two eloquent models Threads and Comments , each thread hasMany comments. 我有两个雄辩的模型ThreadsComments ,每个线程都有很多注释。

While listing the threads, i need to order the threads by the created_at descending. 在列出线程时,我需要按created_at降序对线程进行排序。 So , i need to sort the threads using created at in Comments . 因此,我需要使用在Comments created at对线程进行排序。

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")

It's important to understand how Laravel's eager loading works. 了解Laravel的热切加载方式是很重要的。 If we eager load your example, Laravel first fetches all threads. 如果我们渴望加载您的示例,那么Laravel首先会获取所有线程。 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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM