Skip to content

Commit

Permalink
[10.x] fix: Factory::createMany creating n^2 records (#51225)
Browse files Browse the repository at this point in the history
* fix: Factory::createMany creating n^2 records

* Update Factory.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
calebdw and taylorotwell committed Apr 30, 2024
1 parent 8a65c4d commit 44dba84
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,9 @@ public function createOneQuietly($attributes = [])
*/
public function createMany(int|iterable|null $records = null)
{
if (is_null($records)) {
$records = $this->count ?? 1;
}
$records ??= ($this->count ?? 1);

$this->count = null;

if (is_numeric($records)) {
$records = array_fill(0, $records, []);
Expand Down
16 changes: 16 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,30 @@ public function test_basic_model_can_be_created()
$users = FactoryTestUserFactory::new()->createMany(2);
$this->assertInstanceOf(Collection::class, $users);
$this->assertCount(2, $users);
$this->assertInstanceOf(FactoryTestUser::class, $users->first());

$users = FactoryTestUserFactory::times(2)->createMany();
$this->assertInstanceOf(Collection::class, $users);
$this->assertCount(2, $users);
$this->assertInstanceOf(FactoryTestUser::class, $users->first());

$users = FactoryTestUserFactory::times(2)->createMany();
$this->assertInstanceOf(Collection::class, $users);
$this->assertCount(2, $users);
$this->assertInstanceOf(FactoryTestUser::class, $users->first());

$users = FactoryTestUserFactory::times(3)->createMany([
['name' => 'Taylor Otwell'],
['name' => 'Jeffrey Way'],
]);
$this->assertInstanceOf(Collection::class, $users);
$this->assertCount(2, $users);
$this->assertInstanceOf(FactoryTestUser::class, $users->first());

$users = FactoryTestUserFactory::new()->createMany();
$this->assertInstanceOf(Collection::class, $users);
$this->assertCount(1, $users);
$this->assertInstanceOf(FactoryTestUser::class, $users->first());

$users = FactoryTestUserFactory::times(10)->create();
$this->assertCount(10, $users);
Expand Down

0 comments on commit 44dba84

Please sign in to comment.