我知道这是一些转储错误,但是我暂时无法找到它。我有多对多的表餐和表成分。要输入一些假数据并创建Ingredient_meal表。我在下面发布了一些代码,但是当我使用db:seed --class = MealSeeder时,出现此错误
SQLSTATE [HY000]:常规错误:1364字段'title'没有默认值(SQL:插入meals
(updated_at
,created_at
)值(2020-05-29 16:26:55,2020-05-29 16:26:55))
猜测该工厂无法正常工作,但无法在任何地方找到解决方案,我可以通过将nullable()放入迁移和更新数据来解决此问题,但这似乎不对劲。预先感谢您的帮助!
MealFactory.php
$factory->define(App\Meal::class, function (Faker $faker) {
return [
'title' => $faker->realText($maxNbChars = 10),
'description' => $faker->realText($maxNbChars = 20),
];
});
$factory->define(App\Ingredient::class, function (Faker $faker) {
static $id = 1;
return [
'title' => $faker->realText($faker->numberBetween(10,15)),
'slug' => $id++, //$faker->unique()->numberBetween(1,20),
];
});
Meal.php模型
protected $fillable = ['title','description'];
public function ingredients()
{
return $this->belongsToMany('App\Ingredient');
}
Model Ingredient.php
protected $fillable = ['title'];
public function meals()
{
return $this->belongsToMany('App\Meal');
}
膳食迁移
Schema::create('meals', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('status')->default('created');
$table->string('category')->nullable();
$table->timestamps();
//$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
MealSeeder.php
factory(App\Meal::class, 10)->create()->each(function ($meals) {
$meals->ingredients()->save(factory(App\Ingredient::class)->make());
});
factory(App\Ingredient::class, 10)->create()->each(function ($ingredients) {
$ingredients->meals()->save(factory(App\Meal::class)->make());
});
// Get all the ingredients attaching up to 3 random ingredient to each meal
$ingredients = App\Ingredient::all();
// Populate the pivot table
App\Meal::all()->each(function ($meal) use ($ingredients) {
$meal->ingredients()->attach(
$ingredients->random(rand(1, 3))->pluck('id')->toArray()
);
});
编辑: 我继续前进,没有找到正确的解决方案。我在迁移中设置了nullable()属性,以表示'title'和'description'属性。运行seeder,然后填写所有空的数据,放入DB :: update。现在看起来很丑:(