【问题标题】:can't orderBy accessor in Laravel无法通过 Laravel 中的访问器订购
【发布时间】:2021-07-15 08:46:38
【问题描述】:

我不能按点订购。积分是存取器。

控制器:

$volunteers = $this->volunteerFilter();
$volunteers = $volunteers->orderBy('points')->paginate(10);

志愿者模型:

public function siteActivities()
{
    return $this->belongsToMany(VolunteerEvent::class, 'volunteer_event_user', 'volunteer_id', 'volunteer_event_id')
        ->withPivot('data', 'point', 'point_reason');
}

public function getPointsAttribute(){
    $totalPoint = 0;
    $volunteerPoints = $this->siteActivities->pluck('pivot.point', 'id')->toArray() ?? [];
    foreach ($volunteerPoints as $item) {
        $totalPoint += $item;
    }

    return $totalPoint;
}

但我尝试sortyByDesc('points') 认为它有效但无效。因为paginate(10)limit(10)。所以它不会对所有数据进行排序,只对 10 个数据进行排序。

然后我尝试使用 datatable/yajra。它工作得很好,但我有很多数据。所以问题就出来了

错误代码:内存不足

【问题讨论】:

  • orderBy 是一个数据库查询指令,您的访问器是仅存在于您的 laravel 项目中的东西......您将不得不找到一种方法来使用 laravel 查询构建器 raw 来描述该访问器,例如
  • 我明白,但我的查询很长。我不能写“原始查询生成器”
  • $this->volunteerFilter();这堂课很长
  • 能否将您的代码添加为文本,以便即使图像被删除,问题仍然可以理解?

标签: php laravel sql-order-by accessor


【解决方案1】:

您可以直接在查询中聚合列

$volunteers = $this->volunteerFilter();
$volunteers = $volunteers->selectRaw('SUM(pivot.points) AS points)')->orderByDesc('points')->paginate(10);

【讨论】:

  • 哦,您必须将 pivot 替换为您的数据透视表的实际名称。很抱歉。
  • $volunteers = Volunteer::with(['_region', 'siteActivities']) ->selectRaw('SUM(volunteer_event_user.point) AS points)') ->orderByDesc('points') ->分页(10);
猜你喜欢
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多