Laravel seed 在数据库中创建了错误的行数

Laravel seed create wrong number of rows in DB

我正在尝试创建具有关系的播种机

public function run()
{
    factory(Company::class, 10)->create()->each(function ($company){
        $company->buildings()->saveMany(factory(Building::class, 5)->create()->each(function ($building){
            $building->facilities()->saveMany(factory(App\Models\Facility::class,5)->make());
        }));
    });
}

该代码应创建 10 个公司,每个公司有 5 个建筑物,每个建筑物有 5 个设施。 公司 10 建筑物 50 设施 250

但我明白了

公司 300 建筑物 310 设施 250 这没有意义

我的工厂:

$factory->define(Company::class, function (Faker $faker) {
    $name = $faker->lastName;
    $company = $name.' Company';
    return [
        'name' => $company,
        'shortName' => $name
    ];
});
$factory->define(Building::class, function (Faker $faker) {
    return [
        'name' => 'Hotel '.$faker->lastName,
        'company_id' => function () {
            return factory(App\Models\Company::class)->create()->id;
        }
    ];
});
$factory->define(Facility::class, function (Faker $faker) {
    $elements = array('lavabo','ducha');

    return [
        'name' => $faker->randomElement($elements).' '.$faker->numerify('Habitacion ###'),
        'building_id' => function () {
            return factory(App\Models\Building::class)->create()->id;
        }
    ];
});

还有 databaseSeeder.php

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserSeeder::class);
        $this->call(CompaniesSeeder::class);
    }
}

解决方案

问题出在这里:

$company->buildings()->saveMany(factory(Building::class, 5)->create()->each(function ($building){
    $building->facilities()->saveMany(factory(App\Models\Facility::class,5)->make());
}));

每次您创建一个新的建筑物和设施时,它也在您的工厂中创建一个新的公司。

只需将适当的参数传递给您的 create 函数,让 Faker 知道不要创建新公司和建筑物。

更改自:

factory(Building::class, 5)->create()

收件人:

factory(Building::class, 5)->create(['company_id' => $company->id]);

并对 Facility 应用相同的逻辑。

factory(App\Models\Facility::class,5)->make(['building_id' => $building->id])

旁注

您还可以通过像这样替换回调函数来简化您的工厂:

$factory->define(Building::class, function (Faker $faker) {
    return [
        'name' => 'Hotel '.$faker->lastName,
        'company_id' => factory(Company::class),
    ];
});