Skip to content

[7.x] Add the ability to makeMany (create many without saving) - #33021

Merged
taylorotwell merged 3 commits into
laravel:7.xfrom
ahmedsayedabdelsalam:7.x
Jun 5, 2020
Merged

[7.x] Add the ability to makeMany (create many without saving)#33021
taylorotwell merged 3 commits into
laravel:7.xfrom
ahmedsayedabdelsalam:7.x

Conversation

@ahmedsayedabdelsalam

@ahmedsayedabdelsalam ahmedsayedabdelsalam commented May 30, 2020

Copy link
Copy Markdown
Contributor

when adding many records to a one to many relation I found that I had to use one of two methods

  • createMany($models)
  • saveMany($models)
    but each of them, execute count($models) queries

I found that I had to use the query builder insert method which takes an array of arrays and executes a single query but then I have to explicitly attach the foreign key first

so I thought what if there is a like (make) function but make a collection of instances instead of a single one and every instance has the parent id attached to it under the hood.

I used it in my project as a macro but I thought it could be useful.

public function orderTickets(string $email, int $ticket_quantity)
{
    $order = $this->orders()->create(['email' => $email]);

    $order->tickets()->insert($order->tickets()->makeMany(collect()->pad($ticket_quantity, []))->toArray());

    return $order;
}

@taylorotwell
taylorotwell merged commit 6dee073 into laravel:7.x Jun 5, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants