I'm modeling and seeding the following models using Laravel 9 and Eloquent:
- Organization (1-n)
- organizations_users (pivot)
- User (1-n)
To seed that model, I followed the documentation and used has()
and recycle()
methods.
database/seeders/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// Organisations et users
$organizations = Organization::factory()
->count(10)
->create();
$users = User::factory()
->recycle($organizations)
->has(Organization::factory()->recycle($organizations)->count(1))
->count(10)
->create();
}
When I run the migration with ->has(Organization::factory()->count(1))
, I'm getting 20 organizations in database instead of 10.
It seems the Organizations are not recycled for the relationships and a new Organization is created for each relationship.
What am I doing wrong? Am I able to seed the relations on a separate call after having seeded the users and the organizations?