Search code examples
phpmysqllaraveleloquentmany-to-many

Is there an eager "inserting" option in laravel for ManyToMany attach?


Is there a way to reduce many Insert queries to 1 when using Laravel's attach function in ManyToMany relationship?

Here is my code:

$itemIds = Item::pluck('id');

$sale = Sale::create();

foreach ($itemIds as $id) {
    $sale->items()->attach($id);
}

But this way it makes as many queries as items found in the database.


Solution

  • Attaching / Detaching

    For convenience, attach and detach also accept arrays of IDs as input.

    For example:

    $user = User::find(1);
     
    $user->roles()->attach([1, 2, 3]);
    

    In your code, you have to use $itemIds as array of Item Id.

    $itemIds = Item::pluck('id');
    
    $sale = Sale::create();
    
    $sale->items()->attach($itemIds);