【发布时间】:2021-03-11 21:28:26
【问题描述】:
我的模型是User、Post 和Category。
我正在尝试使用工厂来播种所有数据。 第一级(有帖子的用户)可以正常工作
// Create random users
User::factory()
->times(10)
->hasPosts(10)
->hasCategories(1)
->create();
但我希望每个帖子都有一个类别。 我试过这样做(基于this article):
User::factory()
->times(10)
->has(
PostFactory::times(5)
->hasCategories(1)
->create()
)
->hasCategories(1)
->create();
但是会抛出这个错误:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`description`, `updated_at`, `created_at`) values (odio facilis molestiae, 2020-11-29 21:22:50, 2020-11-29 21:22:50))
更新:添加了简化的迁移
帖子和类别通过many to many链接起来
用户迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
...
});
}
发布迁移
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->text('title');
$table->bigInteger('user_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
类别迁移
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
【问题讨论】:
标签: laravel eloquent factory laravel-8