如何在 Laravel 中使用 Faker 填充嵌套类别 table?

How to populate a nested category table with Faker in Laravel?

我想把子类别id放到引号里table但是好像太复杂了!这是我的尝试,显然它以循环结束。

这是播种机:

public function run()
{
    factory(App\User::class, 50)->create()->each(function ($u) {

        $u->quotes()->save(
            factory(App\Quote::class)->make()
        );

    });
}

以及报价工厂:

return [
    'text' => $faker->paragraph,
    'author_id' => factory('App\Author')->create()->id,
    'category_id' => factory('App\Category')->create()->id
];

类别工厂:

return [
    'name' => $faker->text,
    'parent_id' => factory('App\Category')->create()->id
];

只要你使用Laravel >=5.3,我建议使用states

对于您的默认类别工厂,使 parent_id = null 例如

$factory->define(App\Category::class, function (Faker $faker) {
    return [
        'name'      => $faker->text,
        'parent_id' => null
    ];
});

然后你可以添加一个状态工厂来包含父类别:

$factory->state(App\Category::class, 'child', function ($faker) {
    return [
        'parent_id' => factory('App\Category')->create()->id,
    ];
});

要使用状态,您只需要使用状态名称链接一个名为 states() 的方法,例如

factory(App\Category::class)->states('child')->make();

如果您使用 Laravel <=5.2 那么我建议保留 parent_id = null 然后手动传递 parent_id 例如

$parent = factory(App\Quote::class)->create();
$u->quotes()->save(
    factory(App\Quote::class)->make(['parent_id' => $parent->id])
);

我还建议将来自工厂内部的任何工厂调用包装在闭包中。

'parent_id' => function () {
   return factory('App\Category')->create()->id;
}

这种方式只会在需要时创建模型。如果您曾经通过传递自己的 id 来覆盖该值,它实际上不会触发该函数,就好像它没有包装在闭包中一样,无论您是否传递 id 来覆盖它,它都会调用工厂。

查看 documentation 了解更多信息。