【问题标题】:Model factory access Faker inside state function模型工厂访问 Faker 内部状态函数
【发布时间】:2021-06-05 09:14:11
【问题描述】:

使用 Laravel Eloquent 工厂生成伪造数据,这对于大多数逻辑来说非常有用。我怎样才能需要将数据传递给 state 函数但仍然使用 faker?

例如,为“合同”选择一个介于“职位”设置的最低/最高工资之间的工资。

$positions = Position::factory()
    ->state(function() use($team) {
        return ['team_id' => $team->id];
    })
    ->count(5)
    ->create();

foreach($positions as $position) {
    $contract = Contract::factory()
        ->for($position)
        ->state(function () use ($position) {
            return [
                'salary' => $this->faker->randomFloat(2, $position->salary_min, $position->salary_max),
            ];
        })
        ->count(1)
        ->create();
}

此代码抛出错误无法访问受保护的属性伪造者。

【问题讨论】:

    标签: laravel laravel-8


    【解决方案1】:

    Laravel factory faker 只是 Generator 类的一个实例,你可以使用服务容器获取你的实例:

    use Faker\Generator;
    foreach($positions as $position) {
        $faker = resolve(Generator::class);
        $contract = Contract::factory()
            ->for($position)
            ->state(function () use ($position) {
                return [
                    'salary' =>$faker->randomFloat(2, $position->salary_min, $position->salary_max),
                ];
            })
            ->count(1)
            ->create();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-06
      • 2019-03-24
      • 2021-07-22
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2014-12-12
      • 2021-06-29
      • 1970-01-01
      相关资源
      最近更新 更多