2017-08-01 82 views
1

试图想想替代方法以从我的API中获得我需要的东西。Laravel通过模型上的方法排序关系

我使用Laravel Spark和沿的线路查询:

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

在团队模式的用户关系是:

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

我目前通过现场上订购此用户表,但我也想通过用户模式下的方法订购:

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

T啊,我查询下返回此数据我目前添加此:

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

有没有一种方法,我可以订购由他们queueLength的$ team->用户?

+0

将队列长度作为属性添加到模型中? [看到这个问题](https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load) – milo526

+0

queueLength是怎么回事?如果它来自其他数据库表,则可以进行连接以允许按顺序排序。 –

回答

0

一个解决方案将使用集合sortBy

首先将queueLength作为属性。

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

然后用收集sortBy

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

PS:这会不会是一个好主意,如果你有大量的数据,或者使用分页。

+0

非常感谢! :) – Lovelock