简体   繁体   English

Laravel在模型上按方法排序关系

[英]Laravel order a relation by method on the model

Trying to think of alternate ways to get what I need from my API. 尝试思考从我的API获取我所需要的替代方法。

I am using Laravel Spark and have a query along the lines of: 我正在使用Laravel Spark并按以下方式进行查询:

$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? 有什么办法可以按他们的queueLength命令$ team-> users?

One solution will be use collection sortBy . 一种解决方案是使用collection sortBy

First make queueLength as an attribute. 首先将queueLength作为属性。

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

Then use collection sortBy 然后使用集合sortBy

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

PS: this will not be a good idea if you have huge amount of data or using pagination. PS:如果您有大量数据或使用分页,这将不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM