php - 如何播种与自身有关系的模型
问题描述
我正在使用 Laravel 8 和 PHP v7.4 我有一个模型,它的模式是通过以下迁移生成的。
创建竞赛表
public function up()
{
Schema::create('contests', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('contest_id')->nullable();
$table->foreign('contest_id')->references('id')->on('contests');
});
}
一个contest
可以有很多contests
。为此,我生成了一个工厂类。
竞赛工厂
public function definition()
{
return [
'name' => $this->faker->paragraph(),
];
}
比赛播种机
public function run()
{
\App\Models\Contest::factory(10)->create([
'contest_id' => array_rand(\App\Models\Contest::all()->pluck('id')->toArray())
]);
}
以上引发以下错误。
ErrorException array_rand(): 数组为空
我怎么解决这个问题?
解决方案
当您进行查询以提取信息时,尚未创建记录。您可以create()
不带参数调用,以便创建记录,然后您可以迭代返回的集合:
\App\Models\Contest::factory(10)->create()->each(...);
推荐阅读
- ember.js - Ember 3.16 Octane - 组件未显示在 Application.hbs 中
- java - 如何在没有实体类的情况下运行(插入)存储过程?
- r - 循环遍历R中的数据框列
- python-3.x - 通过python列表函数中的参数传递值
- mysql - 如何通过分组和MySql中的文件数获得结果
- java - 在 Apache Camel 中打印异常堆栈跟踪
- xamarin - 如何在 Xamarin.Mac 应用程序中找到指向非公共框架的链接
- node.js - 当字符串在 MongoDB 中带有括号时,在正则表达式搜索期间出现错误
- javascript - 如何访问 VueJS 组件中的 Sequelize 实例?
- jwt - Postman - 使用密钥文件进行 JWT 身份验证