【发布时间】:2018-12-04 05:20:07
【问题描述】:
我的用户模型上有一个 hasMany 关系
public function timesheet()
{
return $this->hasMany('App\TimeTable', 'employee');
}
我想要一列的总和
$users = User::select('firstname','lastname')->with('timesheet')->get();
foreach($users as $user) {
//sume of $user->timesheet
//tried $user->timesheet->sum('minutes') which return on each iteration 0
}
获得正确结果的最佳方法是什么?
问题在于我在用户对象上使用选择文件的问题。另一方面,这笔钱真的很贵,我得到Allowed memory size of 1073741824 bytes exhausted
【问题讨论】:
-
$user->timesheet的内容是否正确?$user->timesheet->pluck('minutes')的结果是什么? -
$total = $user->timesheet->sum('minutes');应该可以工作。在 foreach 循环中执行dd($user->timesheet);时会看到什么。您应该能够在那里看到所有相关的时间表条目。如果没有,您可能需要检查您的密钥和/或查询(调试栏包)。除此之外,您的代码肯定会变慢,因为它当前会获取所有用户以及每个用户与其关联的所有时间表条目。 -
我更新了!
标签: laravel-5 model eloquent sum relationship