我有一个工厂被调用了好几次,但在contract_year
列上我得到了相同的值。
$factory->define(ContractYear::class, function (Faker $faker) {
$contract = Contract::orderByDesc('id')->first();
$contract_year = ContractYear::select('contract_year')->orderByDesc('id')->value('contract_year');
if($contract_year == null){
$contract_year = 2019;
}
return [
'contract_id' => $contract->id,
'contract_year' => $contract_year++,
'licensed_users' => $faker->randomDigit,
];
});
我从这里开始称呼它。。
$u->contracts()->saveMany(factory(Contract::class, rand(1, 5))->create()->each(function ($contract){
$contract->years()->saveMany(factory(ContractYear::class, $contract->number_of_years)->create());
}));
您可以使用static
$factory->define(ContractYear::class, function (Faker $faker) {
static $contract_year;
$contract = Contract::orderByDesc('id')->first();
if(!$contract_year) {
$contract_year = ContractYear::select('contract_year')->orderByDesc('id')->value('contract_year') ?? 2019;
}
return [
'contract_id' => $contract->id,
'contract_year' => $contract_year++,
'licensed_users' => $faker->randomDigit,
];
});
引用:函数中的"static"关键字?
将计数器连接到$this
$factory->define(ContractYear::class, function (Faker $faker) {
$this->sequences = $this->sequences ?? [];
$contract = Contract::orderByDesc('id')->first();
$group = $contract->id ?? 0;
$this->sequences[$group] = $this->sequences[$group] ?? 2019;
return [
'contract_id' => $contract->id,
'contract_year' => $this->sequences[$group]++,
'licensed_users' => $faker->randomDigit,
];
});
可能值得一看Laravel 8新的模型工厂,以获得更明确的面向对象方法