【发布时间】:2021-07-07 08:30:07
【问题描述】:
我的页面上出现了类似上述标题的错误。 我正在尝试使用 Laravel Excel 扩展名导出 Excel。
这是我的代码:
public function query()
{
$test = Leave::query()
->join('departments as dep', 'leaves.department_id', '=', 'dep.id')
->join('employees as emp', 'leaves.employee_id', '=', 'emp.id')
->join('users as emplUser', 'emp.user_id', '=', 'emplUser.id')
->join('users as apprUser', 'leaves.approved_by_id', '=', 'apprUser.id')
->select('leaves.id',
'dep.name',
'emplUser.first_name',
'leaves.start',
'leaves.end',
'leaves.type',
'leaves.reason',
'leaves.approved',
'leaves.approved_on',
'apprUser.first_name',
'leaves.approved_comment',
'leaves.created_at',
'leaves.updated_at',
)
->whereDate('leaves.start','>=', $this->periodStart)
->whereDate('leaves.end', '<=', $this->periodEnd);
return $test;
}
这是错误消息中的 SQL:
select
`leaves`.`id`,
`dep`.`name`,
`emplUser`.`first_name`,
`leaves`.`start`,
`leaves`.`end`,
`leaves`.`type`,
`leaves`.`reason`,
`leaves`.`approved`,
`leaves`.`approved_on`,
`apprUser`.`first_name`,
`leaves`.`approved_comment`,
`leaves`.`created_at`,
`leaves`.`updated_at`
from `leaves`
inner join `departments` as `dep` on `leaves`.`department_id` = `dep`.`id`
inner join `employees` as `emp` on `leaves`.`employee_id` = `emp`.`id`
inner join `users` as `emplUser` on `emp`.`user_id` = `emplUser`.`id`
inner join `users` as `apprUser` on `leaves`.`approved_by_id` = `apprUser`.`id`
where date(`leaves`.`start`) >= 2021-07-04 and date(`leaves`.`end`) <= 2021-12-31
and (`department_id` = 2 or `department_id` is null)
order by `leaves`.`id` asc limit 1000 offset 0
我注意到上面写着:
where ... and (`department_id` = 2 or `department_id` is null)
但是我从来没有指定department_id,就像开始和结束日期一样。我认为它需要像leaves.department_id,但是当我从第一次开始就没有写过它时,我该怎么做呢?
更新更多代码:
这是来自 LeaveController:
public function export()
{
$now = Carbon::now()->startOfWeek(Carbon::SUNDAY);
$start = $now;
$end = $now->copy()->endOfYear();
$period = new Period($start, $end);
return (new LeavesExport)->forPeriod($period->start, $period->end)->download('download.xlsx');
}
这是 Leave 中的一些代码,我发现它以某种方式包含部门:
use App\Traits\HasDepartment;
* App\Leave
* @property int $department_id
* @property-read \App\Department $department
* @method static \Illuminate\Database\Eloquent\Builder|\App\Leave whereDepartmentId( $value )
class Leave extends Model
{
use HasDepartment, ...
public static function getTypes()
{
try {
return LeaveType::where('department_id', current_department()->id)->pluck('name', 'id');
} catch (\Exception $e) {
error_log('User id: ' . auth()->user()->id . ' does not have an assigned Department');
return collect([]);
}
}
}
【问题讨论】:
-
也许
Leave应用了Leave::query()附带的默认范围 -
您发布的查询/代码似乎不是生成错误消息的查询。错误消息是指对
department_id的限制,但这不会出现在您的代码中。 -
也许您可以将调用此查询函数的函数添加到您的问题中?
-
全局范围或为 Leave 添加的范围似乎是罪魁祸首。在您的项目中搜索 addGlobalScope 或像这样 User::withoutGlobalScopes() 开始查询以查看它是否有帮助
-
现在我已经更新了一些来自 LeaveController 和 Leave 的代码