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

N^2 models created when using EloquentFactory::createMany in conjunction with a count #51224

Closed
calebdw opened this issue Apr 26, 2024 · 1 comment · Fixed by #51225
Closed

Comments

@calebdw
Copy link
Contributor

calebdw commented Apr 26, 2024

Laravel Version

10.x

PHP Version

8.2.x

Database Driver & Version

No response

Description

Hello!

I noticed a subtle bug in the EloquentFactory method when it's using in conjunction with a factory count. The createMany should return an EloquentCollection of models (i.e., a flat structure):

/**
* Create a collection of models and persist them to the database.
*
* @param int|null|iterable<int, array<string, mixed>> $records
* @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>
*/
public function createMany(int|iterable|null $records = null)

However, when the factory has a count provided, a collection of collections is returned, and n^2 models are created:

// expected a collection of 3 models
// returns a collection of 3 collections with 3 models each---9 records total
User::factory()->count(3)->createMany();

I have a PR ready to go to fix this, but I just need some clarification on the expected behaviour when there's both a count and an argument passed to createMany:

User::factory()->count(2)->createMany(3); // ?

Should:

  1. the createMany arg override the count (3 models returned)?
  2. the count override the createMany arg (2 models returned)?
  3. the counts be added together (5 models returned)?
  4. the counts be multiplied together (6 models returned)?

Note that an iterable (states) could also be passed to createMany which would normally create that many records.
It may be more trouble than it's worth to try to bring the count into the mix, so it may be easiest just to have the createMany override the count (Option 1).

Example:

User::factory()->count(2)->createMany([['foo' => 1], ['foo' => 2], ['foo' => 3]]);

Options:

  1. Three records are created with the states passed to createMany
  2. Two records are created, but do you just ignore the last state passed?
  3. Five records are created, but which states are repeated?
  4. Six records are created with the states being repeated twice

Thanks!

Steps To Reproduce

See above

@driesvints
Copy link
Member

Thank you. It seems you already sent in a PR so let's see how it goes.

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 a pull request may close this issue.

2 participants