php - 如果未找到设置为 null,则获取所有带有 sum 的行 - Laravel Eloquent
问题描述
我有两个模型:Employee
和WorkingDay
.
//Employee Model
public function workingDays()
{
return $this->hasMany(WorkingDay::class, 'employee_id','id');
}
public function scopeTotalHours($query, $from, $to)
{
$query->whereHas('workingDays', function ($query) use ($from, $to) {
$query->whereBetween('work_date', [$from, $to]);
})->withSum('workingDays', 'hours_work');
}
我想收到指定日期之间每个员工的小时数。但是如果表中不存在员工working_days
,则将值设置为0
或null
//Query
Employee::totalHours($week->start->toDateTimeString(), $week->end->toDateTimeString())->get()
如果employee_id
不存在于working_days
:
items = []
但我想要这样的东西:
Between: 2020-10-31 and 2020-11-05
items = [
all employees with additional column: sum of hours
Employee fields, 25 //exists
Employee fields, 0 or null //doesnt exist
]
可以使用查询生成器来做到这一点吗?
谢谢
解决方案
推荐阅读
- php - 在 PHP 中使用计数器确定结果
- r - 如何为 mxnet 安装 R 包?
- mysql - 特殊选择语句。根据其主要 SKU 选择所有 SKU
- elm - 榆树和单选按钮摇晃
- python - python3模块导入/命名困境
- java - 我需要仅使用循环替换数组中的字符。我不能做比这更高级的事情了。我应该怎么办?
- android - xml上的Android数据绑定注册侦听器用于自定义按钮
- r - 因果影响 R 包中的置信区间
- c++ - CMake 无法找到 Boost 库(VS 2017)
- hadoop - 我是hadoop的新手,正在学习基础知识。我最近安装了沙箱,但我无法运行 Hadoop 命令