【问题标题】:Laravel order a relation by method on the modelLaravel 在模型上按方法排序关系
【发布时间】:2018-01-08 09:50:52
【问题描述】:

试图想出其他方法来从我的 API 中获取我需要的东西。

我正在使用 Laravel Spark,并有一个查询如下:

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

Team 模型上的用户关系是:

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
}

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

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

有没有一种方法可以让 $team->users 按他们的 queueLength 排序?

【问题讨论】:

  • 将队列长度作为属性添加到模型中? See this question
  • queueLength 是多少?如果它来自其他数据库表,你可以做一个连接来允许它排序。

标签: php laravel


【解决方案1】:

一种解决方案是使用集合sortBy

首先将 queueLength 作为一个属性。

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

然后使用集合排序方式

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 2019-05-14
    • 2020-01-08
    • 2021-10-02
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2017-05-07
    相关资源
    最近更新 更多