无法通过 Laravel 中的访问器订购

问题描述

我不能按积分订购。点是访问器。

控制器:

$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 个数据进行排序。

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

错误代码:内存不足

解决方法

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

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