How to sort an Eloquent subquery

為{幸葍}努か 提交于 2020-01-07 02:45:29

问题


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.


回答1:


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.




回答2:


If you ALWAYS want it sorted by lastname you can also add the sortBy call directly in the relationship function on the model.

    public function teammember() {
    return this->hasMany('Teammember')->orderBy('last_name');
    }

I prefer a separate method in this case as suggested by Darren Taylor to maintain flexibility, but it's nice to know you can chain to the relationship functions directly as well.



来源:https://stackoverflow.com/questions/25105113/how-to-sort-an-eloquent-subquery

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