How to sort an Eloquent subquery

2019-09-06 09:17发布

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.

2条回答
孤傲高冷的网名
2楼-- · 2019-09-06 09:59

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.

查看更多
我只想做你的唯一
3楼-- · 2019-09-06 10:01

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.

查看更多
登录 后发表回答