代码之家  ›  专栏  ›  技术社区  ›  eComEvo

设定工厂关系种子时,“变形”字段没有默认值

  •  0
  • eComEvo  · 技术社区  · 5 年前

    我有一个 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

    0 回复  |  直到 5 年前