编程语言
首页 > 编程语言> > php – Laravel Factory:手动增加列

php – Laravel Factory:手动增加列

作者:互联网

对于以下工厂定义,列顺序需要是顺序的.已经有一个自动递增的列ID.第一行的顺序应该从1开始,每个附加行的顺序应该是下一个数字(1,2,3等)

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => (App\AliasCommand::count()) ?
            App\AliasCommand::orderBy('order', 'desc')->first()->order + 1 : 1
    ];
});

它应该将order列设置为比前一行多1,但是,它会导致所有行都被分配1.

解决方法:

这可能有用.

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    static $order = 1;   
    return [
        'user_id' => App\User::inRandomOrder()->first()->id,
        'command' => $faker->word,
        'content' => $faker->sentence,
        'order'   => $order++
    ];
});

它只是在该函数内部保留一个计数器.

标签:php,laravel,laravel-5-4,laravel-seeding
来源: https://codeday.me/bug/20190715/1465067.html