Home > database >  Data Duplication PHP and Laravel
Data Duplication PHP and Laravel

Time:09-06

Hey colleagues, Below is my code that duplicates database entries what could be the problem folks. When I try to trigger the end point that fetches employees it duplicates the entries multiple times

            $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) { $join->on('employees.position_id', '=', 'positions.id');})
            ->leftJoin('countries', function ($join) { $join->on('employees.country_id', '=', 'countries.id');})
            ->leftJoin('supervisors', function ($join) { $join->on('employees.first_supervisor_id', '=', 'supervisors.id');})
            ->leftJoin('cities', function ($join) { $join->on('employees.city_id', '=', 'cities.id');})
            ->leftJoin('attendance_times', function ($join) { $join->on('employees.attendance_time_id', '=', 'attendance_times.id');})
            ->leftJoin('departments', function ($join) { $join->on('employees.sub_department_id', '=', 'departments.id');})
            ->leftJoin('pay_frequencies', function ($join) { $join->on('employees.pay_frequency_id', '=', 'pay_frequencies.id');})
            ->leftJoin('duty_types', function ($join) { $join->on('employees.duty_type_id', '=', 'duty_types.id');})
            ->leftJoin('rate_types', function ($join) { $join->on('employees.rate_type', '=', 'rate_types.id');})
            ->orderBy('employees.id', 'DESC')
            ->get();

        return $this->customSuccessResponseWithPayload($all_employees);

CodePudding user response:

Try to use the "distinct" with the query to fetch non-repetitive data. DB::table('table')->select('job_id')->distinct()->get();

CodePudding user response:

use with('Relation') while get one to many Relation Data , cuz if u use leftjoin you will get all the relational Data . Ex : Every Employee has many attendance_times so if you create a SQL Query which get all Employees and joined the attendance_times the returned data will contain a duplicated EMP data every time has attendance_times .

Basically use ->with('Relation') .

  • Related