数据复制PHP和Laravel下面的



是我的代码,它重复了数据库条目,问题可能是什么?

当我试图触发提取员工的终点时,它会多次复制条目

$all_employees = Employee::with([
'department',
'sub_department',
'first_supervisor',
'second_supervisor',
'reportingTo',
])
->select(
'employees.*',
'attendance_times.start_time as attendance_time',
'cities.city',
'countries.country',
'pay_frequencies.frequency as pay_frequency',
'duty_types.name as duty_type',
'rate_types.name as rate_type',
'positions.name as  position_name',
'departments.department as sub_department',
'supervisors.name as supervisor_name'
)
->leftJoin('positions', function ($join) {
return $join->on('employees.position_id', '=', 'positions.id');
})
->leftJoin('countries', function ($join) {
return $join->on('employees.country_id', '=', 'countries.id');
})
->leftJoin('supervisors', function ($join) {
return $join->on('employees.first_supervisor_id', '=', 'supervisors.id');
})
->leftJoin('cities', function ($join) {
return $join->on('employees.city_id', '=', 'cities.id');
})
->leftJoin('attendance_times', function ($join) {
return $join->on('employees.attendance_time_id', '=', 'attendance_times.id');
})
->leftJoin('departments', function ($join) {
return $join->on('employees.sub_department_id', '=', 'departments.id');
})
->leftJoin('pay_frequencies', function ($join) {
return $join->on('employees.pay_frequency_id', '=', 'pay_frequencies.id');
})
->leftJoin('duty_types', function ($join) {
return $join->on('employees.duty_type_id', '=', 'duty_types.id');
})
->leftJoin('rate_types', function ($join) {
return $join->on('employees.rate_type', '=', 'rate_types.id');
})
->orderBy('employees.id', 'DESC')
->get();
return $this->customSuccessResponseWithPayload($all_employees);

在获取一对多关系的数据时使用with('Relation'),因为如果使用leftJoin,将再次获取所有关系的数据。

示例:
每个员工都有许多attendance_times,因此,如果您创建一个SQL查询来获取所有Employees并加入attendance_times,则每次返回的数据都会包含重复的EMP数据attendance_times

基本上使用->with('Relation')

尝试将distinct与查询一起使用以获取非重复数据。

DB::table('table')
->select('job_id')
->distinct()
->get();

它可以通过在查询末尾添加groupBy(employees.id)来解决,这就是我解决它的方法

最新更新