skip to Main Content

I’m trying to eliminate duplicates from a table but the query I’m using deletes the entire database and not the duplicates, can you tell me why and what I can do? Thank you very much in advance to the whole community..

This is code

$ids = EsitiAudit::
groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])->get(['id'])->all();

EsitiAudit::whereNotIN('id', $ids)->delete();

2

Answers


  1. You’re passing complete elements to the ->delete() query, try this instead:

    $esitiAudits = EsitiAudit::groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])->get(['id']);
    
    $ids = $esitiAudits->pluck('id')->toArray();
    
    EsitiAudit::whereNotIn('id', $ids)->delete();
    

    Pick just the ids from the elements on the query and then delete the files.

    Login or Signup to reply.
  2. $ids = EsitiAudit::select('id')
    ->groupBy(['master_zone', 'subarea', 'microarea', 'frequency_audit', 'data_audit', 'esito', 'employee', 'eseg_riass', 'categoria'])
    ->havingRaw('COUNT(id) > 1')
    ->get();
    
    $idsToDelete = $ids->pluck('id')->toArray();
    
    EsitiAudit::whereNotIn('id', $idsToDelete)->delete();
    
    1. we have to check whether the id is present multiple times or not by checking the count.
    2. Next, we use pluck(‘id’) to extract the id values from the result.
    3. we use whereNotIn with the extracted idsToDelete to delete the duplicate rows that are not in the list of IDs to keep.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search