首页 > 解决方案 > 如果未找到设置为 null,则获取所有带有 sum 的行 - Laravel Eloquent

问题描述

我有两个模型:EmployeeWorkingDay.

//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,则将值设置为0null

//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
]

可以使用查询生成器来做到这一点吗?

谢谢

标签: phplaraveleloquent

解决方案


推荐阅读