我有两个表“ Employee”和“ EmployeeLeaveLog”。 我正在尝试使用下面的代码获取员工当月离职记录的记录,但这向我显示了一个错误。
我要放在whereRaw()中的sql代码是:
SELECT * FROM employee_leave_log
WHERE UNIX_TIMESTAMP(from_date) >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) +
INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND ( (till_date IS NULL) OR (UNIX_TIMESTAMP(till_date) <
UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY)));
Laravel代码是:
Employee::with(['leaveRecord' => function($query){
$query->whereRaw("((UNIX_TIMESTAMP(from_date) >=
(UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH)))
AND ( (till_date IS NULL) OR (UNIX_TIMESTAMP(till_date) <
UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY))))");
} ])->all();
编辑:
EmployeeLeaveTable具有以下主要列:
leave_log_id,
employee_id,
from_date,
till_date(如果仅请假一天,则为Null。)
修改2: 我发现我在whereRaw()中放入的SQL代码出现逻辑错误。
正确的SQL代码应为:
SELECT * FROM employee_leave_log
WHERE (
(
(UNIX_TIMESTAMP(from_date) >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH))
AND
(UNIX_TIMESTAMP(from_date) < UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY))
)
OR
(
(UNIX_TIMESTAMP(till_date) >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH))
AND
(UNIX_TIMESTAMP(till_date) < UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY))
)
);
答案 0 :(得分:1)
回答我自己的问题。最终我发现了这个问题,SQL语句中存在逻辑错误。
以下代码应该可以工作:-
CORS_ALLOW_CREDENTIALS = True
答案 1 :(得分:0)
要获取当前月份的假期,您可以执行以下操作:
Employee::with(['leaveRecord' => function ($query) {
$query->whereDate('from_date', '>=', Carbon::now()->startOfMonth());
$query->whereDate('till_date', '<=', Carbon::now()->endOfMonth());
}])->get();
答案 2 :(得分:0)
您遇到哪种错误?
您可以尝试以下方法:
Employee::with(['leaveRecord' => function ($query) {
$query->whereDate('from_date', '>=', Carbon::now()->startOfMonth())
->whereNull('till_date')
->orWhereDate('till_date', '<=', Carbon::now()->endOfMonth());
}])->get();
更新,请尝试以下操作:
Employee::with(['leaveRecord' => function ($query) {
$query->whereDate('from_date', '>=', Carbon::now()->startOfMonth())
->where(function ($query) {
return $query->whereNull('till_date')
->orWhereDate('till_date', '<=', Carbon::now()->endOfMonth());
});
}])->get();
这应将第二部分包装在()
中以解决此问题。