【发布时间】:2020-03-31 10:46:20
【问题描述】:
我有以下迁移(对于数据透视表):
Schema::create('category_news', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('news_id');
$table->unique(['category_id', 'news_id']);
$table->foreign('news_id')->references('id')->on('news')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
我想在该表中植入一些虚拟数据——为此,我创建了以下工厂:
$factory->define(CategoryNews::class, function (Faker $faker) {
return [
'category_id' => $faker->numberBetween($min = 1, $max = 35),
'news_id' => $faker->numberBetween($min = 1, $max = 150)
];
});
但是,当我运行以下命令时:php artisan migrate:fresh --seed,我收到以下错误:
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE) (SQL: insert into `category_news` (`category_id`, `news_id`, `updated_at`, `created_at`) values (16, 13, 2020-03-31 10:44:04, 2020-03-31 10:44:04))
at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE)")
2 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
知道为什么以及我需要做些什么来修复它吗?
谢谢。
【问题讨论】: