如何解决无法通过 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。