如何对雄辩的子查询进行排序 [英] How to sort an Eloquent subquery

查看:103
本文介绍了如何对雄辩的子查询进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择了两个表格:团队和成员.这些模型通过n:m关系连接,在我的团队视图中,我将进行一个foreach循环,以使该团队的成员像这样:

I have two tables conected: Team and member. The models are connected by a n:m relationship and in my team views I will make a foreach loop to get the members of said team like this:

@foreach( $team->teammember as $member )
    {{ $member->firstname }} {{ $member->lastname }}
@endforeach

到目前为止,一切都很好并且可以正常工作,我的问题是,如何获取按姓氏排序的成员列表?在我的控制器中,我没有得到成员,因为连接是通过模型完成的,所以我只能对团队进行排序,而不能对成员进行排序.

So far everything is great and working, my issue is, how do I get the members list sorted by lastname? In my controller I'm not getting the members, since the connection is done via the model, I can only sort the teams but not the members.

推荐答案

基本上,您可以这样做:

Essentially, you can do this:

@foreach( $team->teammember()->orderBy('last_name')->get() as $member )
    {{ $member->firstname }} {{ $member->lastname }}
@endforeach

但是,最好将其抽象到模型中,或者如果您打算大量使用它的话.

However, might be best to abstract this into the Model or something if you plan on doing it alot.

这篇关于如何对雄辩的子查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆