Laravel: 使用工厂函数创建外键时出现错误
Laravel: 使用工厂函数创建外键时出现错误
我有以下迁移(用于一个透视表):
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()
有什么想法为什么出错以及我需要做什么来修复它吗?
谢谢。
在使用工厂为外键生成数据时,出现了"使用工厂为外键生成数据时出现的错误"。这个错误的原因是,当尝试添加一个新的记录category_news,其中category_id=16,而数据库中没有id为16的category,因此约束会抛出一个错误。不能使用随机整数来分配给外键引用。解决方法是,在工厂函数中使用以下代码:
$factory->define(CategoryNews::class, function (Faker $faker) { return [ 'category_id' => Category::all()->random()->id, 'news_id' => News::all()->random()->id, ]; });
我在这里找到了这种解决方法:https://stackoverflow.com/a/44102531/10573560