Search code examples
laraveleloquentfetchsynchronization

sync fetch eloquent laravel


i have this array:

  $ingredients_alergens = [
    1285 => [ //id from ingredient
      4, //id from alergen
      2
    ]
    1286 => [
      6
    ]
    1287 => [
      1
    ]
    1288 => [
      9
    ]
  ]

and i want make a massive sync similar to this:

$ingredient->alergens()->sync([1,3,8]);

but with all the array. I want make a únic sync/upsert/something for a full list and don't do query to query. Because i have arrays/jsons from more than a thousand redords.

Are there any way to build a massive sync (into single query, like an upsert) into eloquent laravel?


Solution

  • You have many Ingredients (1285, 1286, 1287, 1288), so you'd need to get all of them first and then, for each of them, sync the relationship.

    You could do it with these 2 lines using your $ingredients_alergens variable:

    $ingredients_alergens = [
        1285 => [4, 2],
        1286 => [6],
        1287 => [1],
        1288 => [9],
    ];
    
    Ingredient::findMany(array_keys($ingredients_alergens)) // findMany([1285, 1286, 1287, 1288])
        ->each(fn(Ingredient $i) => $i->alergens()->sync($ingredient_alergens[$i->id]));
    

    If you do not want sync to delete existing alergens. (For example, you just want to add alergen 9 to ingredient 1288), use syncWithoutDetaching() instead of sync().