首页 > 解决方案 > 无法通过 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。它工作得很好,但我有很多数据。所以问题就出来了

错误代码:内存不足

标签: phplaravelsql-order-byaccessor

解决方案


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

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

推荐阅读