php - 无法通过 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);
推荐阅读
- symfony - Symfony 4:在路由定义中设置 {_locale} 参数会导致“找不到路由”错误
- javascript - 如何选择包含在另一个div中的div中的textarea的整个li
- android - 从 Google Maps API 获取街道信息
- python - ValueError:无法将字符串转换为浮点数:'2,3972E-7'---loadtxt(numpy)
- python - 在python中将具有相同列名的几列以另一列结尾
- ruby-on-rails - 在 Windows 10 上显示图像错误轨道 6 的操作文本
- bash - Bash 使用“?” 作为调用帮助函数的参数
- azure-function-app - Azure Function Apps 混合连接连接到 Azure 负载均衡器
- libreoffice - LibreOffice 链接到参考书目
- javascript - JavaScript:JSON Stringify 和 String() 之间的短路选择取决于输出