从 mysql 查询转换为雄辩的 laravel

问题描述 投票:0回答:1

您好,我想请求将以下查询转换为雄辩的 laravel 的建议。

我在mysql中的查询

SELECT CONCAT(e.lastname,', ',e.firstname,' ',e.middlename) as full_name,
e.emp_id,
t.date,
t.time_in,
t.time_out,
TIME_FORMAT(time_in, "%r") as Ctime_in,    
TIME_FORMAT(time_out, "%r") as Ctime_out,    
TIMEDIFF(time_out,time_in) as number_of_hrs    
FROM `employees` as e LEFT JOIN time_records as t  on e.emp_id = t.emp_id
where t.date = '2024-03-01' OR t.date IS NULL 
GROUP by e.emp_id; 

日期范围“2024-03-01”将是 eloquent($day) 中的变量

到目前为止我的雄辩代码

DB::table('employees')
    ->select(

        DB::raw("CONCAT(employees.lastname,', ',employees.firstname,' ',employees.middlename) as full_name"),

    'employees.emp_id',
    'time_records.date',
    'time_records.time_in',
    'time_records.time_out',
    DB::raw('TIME_FORMAT(time_in, "%r") as Ctime_in'),
    DB::raw('TIME_FORMAT(time_out, "%r") as Ctime_out'),
    DB::raw('TIMEDIFF(time_out,time_in) as number_of_hrs')



       )
    ->leftJoin('time_records', 'time_records.emp_id', '=', 'employees.emp_id')
    ->whereDate('date',$day)
    ->orwhereNull('date',$day)
    ->get();

这个结果给了我与 mysql 不同的输出,我知道我的错误在于日期为空的部分 ->whereDate('date',$day) \ 不知道在哪里包含“OR t.date IS NULL”..

mysql eloquent
1个回答
0
投票

我找到了一个解决方案,虽然我后来在查询中发现了一个错误,但为了解决我自己的问题,我使用了 whereraw 子句

->whereRaw('time_records.date = ? OR time_records.date IS NULL', [$day])
© www.soinside.com 2019 - 2024. All rights reserved.