【问题标题】:How to pass variable in related factory laravel如何在相关工厂laravel中传递变量
【发布时间】:2019-11-11 07:50:53
【问题描述】:

我正在通过 PHP 单元在 Lumen 上创建测试。我尝试将变量 $name 传递给相关的工厂模板 --> 属性。

我已经尝试过这段代码,但没有工作。

        $name = 'Mulyawan Sentosa';
        factory(TemplateModel::class)->create(
            [
                'id'    => 12
            ]
            )->each(
            function ($template) {
                $template->attributes()->save(
                    factory(TemplateattributeModel::class)->make(
                        [
                            'name'      => $name
                        ]
                    )
                );
            }
        );

如何做到这一点?谢谢!

【问题讨论】:

    标签: php laravel factory


    【解决方案1】:

    您需要在use关键字参数中传递变量,才能在闭包函数中使用该变量。

    $name = 'Mulyawan Sentosa';
    
    factory(TemplateModel::class)->create(
                [
                    'id'    => 12
                ]
            )->each(
                function ($template) use($name) {
                    $template->attributes()->save(
                        factory(TemplateattributeModel::class)->make(
                            [
                                'name'      => $name
                            ]
                        )
                    );
                }
            );
    

    欲了解更多信息,visit the PHP documentation

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 2019-01-26
      • 2015-11-29
      • 2020-09-25
      • 1970-01-01
      • 2021-09-26
      • 2021-06-30
      • 1970-01-01
      • 2022-08-17
      相关资源
      最近更新 更多