【问题标题】:Morph field doesn't have a default value when seeding factory relationship播种工厂关系时,Morph 字段没有默认值
【发布时间】:2022-04-28 22:56:33
【问题描述】:

我有一个RecipeReview 模型:

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_typereviewable_id 值?

【问题讨论】:

  • 菜谱和评论之间的关系不是一对多吗?一个评论属于一个食谱,一个食谱有很多评论,对吧?您的 Recipe 模型将 MorphMany 评论而不是 MorphToMany 并且您的 Review 模型将定义 MorphTo 可评论关系。
  • 你说得对,我把它弄反了。但是,更改为 MorphMany 并不能修复出厂错误。
  • 我假设您已从使用 hasAttached 恢复为 Recipe::factory()->has(Review::factory()->count(5))->create()?
  • 解决了!

标签: laravel factory laravel-8


【解决方案1】:

就我而言,我有一个程序和一个表单,该表单可以附加到各种表格。

当我创建播种机时,我会抓取一个程序,创建一个表单,然后收到错误 General error: 1364 Field 'formable_type' doesn't have a default value

我通过更新我的迁移以使用 nullableMorphs 解决了这个问题。

$table->nullableMorphs('formable');

希望对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2018-03-27
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2018-03-19
    相关资源
    最近更新 更多