Laravel通过模型上的方法对关系进行排序

Laravel通过模型上的方法对关系进行排序

问题描述:

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

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

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

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');
}

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();
}

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

尝试考虑从我的API中获取所需内容的其他方法。 p>

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

团队模型上的用户关系是: p>

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

我目前通过users表上的字段对此进行排序,但我还想通过Users模型上的方法进行排序 : p>

  public function queueLength()
 {
 // //返回用户队列长度的整数
} 
  code>  pre> 
  
 

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

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

是否有 我可以通过queueLength订购$ team->用户吗? p> div>

One solution will be use collection sortBy.

First make queueLength as an attribute.

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

Then use collection sortBy

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

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