Laravel Factory:手动增加列 [英] Laravel Factory: Manual Increment of Column
本文介绍了Laravel Factory:手动增加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下工厂定义,列order
必须是连续的.已经有一个列id
,该列会自动增加.第一行的order
应该从1
开始,其他每一行的order
应该是下一个数字(1
,2
,3
等)
For the following factory definition, the column order
needs to be sequential. There is already a column id
that is auto-incremented. The first row's order
should start at 1
and each additional row's order
should be the next number (1
,2
,3
, etc.)
$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
.
It should be setting the order
column to be 1 more than the previous row, however, it results in all rows being assigned 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++
];
});
它只是在该函数内部保留一个计数器.
It just keeps a counter internal to that function.
这篇关于Laravel Factory:手动增加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文