【发布时间】:2022-04-28 22:56:33
【问题描述】:
我有一个Recipe 和Review 模型:
class Recipe extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function reviews(): MorphToMany
{
return $this->morphToMany(Review::class, 'reviewable');
}
}
class Review extends Model
{
use HasFactory;
protected $guarded = ['id'];
}
每个人都有一个工厂:
class RecipeFactory extends Factory
{
protected $model = Recipe::class;
public function definition()
{
return [
'name' => $this->faker->sentence(5, true),
];
}
}
class ReviewFactory extends Factory
{
protected $model = Review::class;
public function definition()
{
return [
'review' => $this->faker->paragraphs(1, true),
];
}
}
当我尝试使用这个来播种新的测试记录时:
Recipe::factory()->hasAttached(
Review::factory()
->count(5)
);
我收到 SQL 错误:
SQLSTATE[HY000]: General error: 1364 Field 'reviewable_type' doesn't have a default value
在播种相关记录时,如何让 Laravel 填写正确的变形 reviewable_type 和 reviewable_id 值?
【问题讨论】:
-
菜谱和评论之间的关系不是一对多吗?一个评论属于一个食谱,一个食谱有很多评论,对吧?您的 Recipe 模型将
MorphMany评论而不是MorphToMany并且您的 Review 模型将定义MorphTo可评论关系。 -
你说得对,我把它弄反了。但是,更改为
MorphMany并不能修复出厂错误。 -
我假设您已从使用
hasAttached恢复为Recipe::factory()->has(Review::factory()->count(5))->create()? -
解决了!