工厂的增量数量,Laravel

jxct1oxe  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(76)

我有一个工厂,它被调用了几次,但是在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());            
}));
wztqucjr

wztqucjr1#

您可以使用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 keyword inside function?

3wabscal

3wabscal2#

将计数器附加到$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新模型工厂,以获得更明确的面向对象的方法

相关问题