Laravel在模型上按方法排序关系 [英] Laravel order a relation by method on the model

查看:573
本文介绍了Laravel在模型上按方法排序关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试考虑从我的API获取我所需要的替代方法.

Trying to think of alternate ways to get what I need from my API.

我正在使用Laravel Spark,并按以下方式进行查询:

I am using Laravel Spark and have a query along the lines of:

$team = Team::with('users')->find($id);

Team模型上的用户关系是:

The users relationship on the Team model is:

public function users()
{
   return $this->belongsToMany(
       'App\User', 'team_users', 'team_id', 'user_id'
   )->withPivot('role')->orderBy('current_active_team', 'DESC');
}

我目前正在通过users表上的字段进行排序,但是我也想通过Users模型上的方法进行排序:

I am currently ordering this by a field on the users table, but I also want to order by a method on the Users model:

public function queueLength()
{
    // returns an integer for the users queue length
}

要返回此数据,我目前正在查询中添加该数据:

To return this data I am currently adding this under my query:

foreach ($team->users as $user) {
    $user->queueLength = $user->queueLength();
}

有没有一种方法可以按用户的queueLength来订购$ team->用户?

Is there a way I can order the $team->users by their queueLength?

推荐答案

一个解决方案是使用集合sortBy.

One solution will be use collection sortBy.

首先将queueLength设置为属性.

First make queueLength as an attribute.

public function getQueueLengthAttribute()
{
    // returns an integer for the users queue length
}

然后使用集合sortBy

Then use collection sortBy

$team->users->sortBy('queueLength');

PS:如果您有大量数据或使用分页,这将不是一个好主意.

PS: this will not be a good idea if you have huge amount of data or using pagination.

这篇关于Laravel在模型上按方法排序关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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