【发布时间】:2019-05-04 11:21:14
【问题描述】:
幼虫 5.6.3 PHP 7.2.10
我收到php artisan migrate:fresh 的以下错误
General error: 1215 Cannot add foreign key constraint (SQL: alter table `videos` add constraint `videos_video_identified_by_foreign` foreign key (`video_identified_by`) references `users` (`id`))
用户表迁移文件 -> 2014_10_12_000000_create_users_table
视频表迁移文件 -> 2018_12_02_122553_create_videos_table
通常当父表不存在并且我们使用它的列作为表中的外键时会发生这种情况,但是可以看出应该首先创建用户表,然后创建视频表,那么为什么我会得到这个错误。
用户表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
视频
Schema::create('videos', function (Blueprint $table) {
$table->increments('video_id');
$table->text('video_link');
$table->text('video_description');
$table->string('video_category');
$table->string('video_language');
$table->unsignedInteger('video_identified_by');
$table->timestamps();
});
Schema::table('videos', function($table) {
$table->foreign('video_identified_by')->references('id')->on('users');
});
【问题讨论】:
-
有时缓存或有时自动加载文件可能会导致此类问题,请清除缓存并运行 composer dumpautoload 命令。
-
@SagarGautam,感谢您的友好回复,我在运行此命令之前运行了
php artisan config:cache和composer dump-autoload仍然收到此错误。 -
user.id 是主键吗?这个约束“videos_video_identified_by_foreign”是否已经存在?我建议你先彻底检查你的数据库是否有任何此类事情。
-
当我尝试为带有关键字
UNSIGNED的列和没有关键字UNSIGNED的列设置键时,我总是遇到这个问题 -
@MelroyFernandes 是的,users 表是默认的 laravel 表,我已经更新了有问题的迁移文件代码,请检查。
标签: php mysql laravel laravel-migrations