dtz63853
2017-08-01 13:32
浏览 704
已采纳

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?

图片转代码服务由CSDN问答提供 功能建议

尝试考虑从我的API中获取所需内容的其他方法。 < 我正在使用Laravel Spark并且有一个查询:

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

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

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

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

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

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

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

是否有 我可以通过queueLength订购$ team-&gt;用户吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douchen7555 2017-08-01 13:44
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题