Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jun 5, 2020
Merged

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

merged 3 commits into from
Jun 5, 2020

Conversation

ahmedsayedabdelsalam
Copy link
Contributor

@ahmedsayedabdelsalam ahmedsayedabdelsalam commented May 30, 2020

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