【问题标题】:How to Run Seeder to Multiple Related Table at Once on Laravel?如何在 Laravel 上一次将 Seeder 运行到多个相关表?
【发布时间】:2019-06-08 21:23:37
【问题描述】:

我正在创建 3 个相互关联的表,如下所示:

Template hasOne Attribute


Template hasOne Link

我想通过模板播种器填充属性和链接表。 我尝试在模板工厂中插入两个函数来一次运行它,但是第二个函数不起作用,只有第一个函数可以正常工作。

我希望它一次运行。

这是我的工厂代码:

factory(App\Models\Template\Eloquent\TemplateModel::class, 10)->create()->each(
    function ($template) {
        $template->links()->save(
            factory(App\Models\Template\Eloquent\TemplatelinkModel::class)->make()
        );
    },
    function ($template) {
        $template->attributes()->save(
            factory(App\Models\Template\Eloquent\TemplateattributeModel::class)->make()
        );
    }
);

如何做到这一点? 请一些身体帮助我?谢谢。

【问题讨论】:

  • 你能用外键显示这些表/模型的表结构吗?
  • 关系正常,现在可以了,谢谢你的意见。

标签: php laravel


【解决方案1】:

您应该只使用一个回调函数作为 Illuminate\Support\Collection->each() 函数的参数。在您的情况下,在作为回调发送到 each() 的同一函数中使用两个保存操作就可以了。

factory(App\Models\Template\Eloquent\TemplateModel::class, 10)->create()->each(
    function ($template) {
        $template->links()->save(
            factory(App\Models\Template\Eloquent\TemplatelinkModel::class)->make()
        );
        $template->attributes()->save(
            factory(App\Models\Template\Eloquent\TemplateattributeModel::class)->make()
        );
    }
);

有关如何使用 each() 和其他 Collection 函数的更多信息,请参阅https://laravel.com/docs/5.8/collections

【讨论】:

  • 酷!有用!太感谢了。你节省了我的时间:)
猜你喜欢
  • 2019-11-18
  • 2019-03-22
  • 2020-11-06
  • 1970-01-01
  • 2017-06-03
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多