有没有办法将mysql转换为laravel雄辩的查询生成器?

时间:2019-09-14 07:28:09

标签: php mysql laravel laravel-query-builder

我想获取当天员工的first_check_inlast_check_out。下面的MySQL代码运行良好,但是我是新手,我不知道如何编写它。对不起,我的英语。

SELECT `employees`.`*`, 
`teams`.`description`, 
`time_groups`.`start`, 
`time_groups`.`end`,
 cast(a1.action_time as date) AS date,
 Min(`a1`.`action_time`) AS `first_check_in`, 
 MAX(`a2`.`action_time`) AS `last_check_out` 
 FROM `employees` 
 JOIN `teams` 
 ON `employees`.`team_id` = `teams`.`id`  
 JOIN `time_groups` 
 ON `teams`.`time_group_id` = `time_groups`.`id`  
 JOIN `attendance_employees` AS a1
 JOIN `attendance_employees` AS a2
 ON `employees`.`id` = `a2`.`employee_id` 
 AND `a1`.`employee_id` = `a2`.`employee_id` 
 AND DATE(a1.action_time) = DATE(a2.action_time)
 WHERE  1 = 1
 AND `a1`.`type` = 1 
 AND `a2`.`type` = 2
 AND DATE(a1.action_time) = CURDATE()
 GROUP BY a1.employee_id, `date`

我在某个时候尝试过

DB::table('employees')
    ->join('teams', 'employees.team_id', '=', 'teams.id')
    ->join('time_groups', 'teams.time_group_id', '=', 'time_groups.id')
    ->join('attendance_employees as a1')
    ->join('attendance_employees as a2',
            function($join) {
                $join->on('employees.id', '=', 'a2.employee_id');
                $join->on('a1.employee_id', '=', 'a2.employee_id');
                $join->on('DATE(a1.action_time)', '=', 'DATE(a2.action_time)');
            }
    )
    ->select(
        'employees.*',
        'teams.description',
        'time_groups.start',
        'time_groups.end'
    )
    ->addSelect('cast(A1.action_time as date)')->alias('date')
    ->addSelect('a1.action_time')->alias('check_in')
    ->addSelect('a2.action_time')->alias('check_out')
    ->where(1,1)
    ->where('a1.type', 1)
    ->where('a2.type', 2)
    ->groupBy('employee_id')
    ->groupBy('date')

但是出现以下错误:

  

SQLSTATE [42S02]:未找到基表或视图:1146表   'db.attendance_employees as a1'不存在

0 个答案:

没有答案