php - 尝试使用 Laravel 迁移添加外键约束时出错
问题描述
我正在尝试找出外键,但是在添加:$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
到我的代码后尝试迁移时,出现此错误:
"SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `images` add constraint `images_user_id_foreign` foreign key
(`user_id`) references `users` (`id`) on delete cascade)
"
用户迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('username');
$table->string('password');
$table->string('email');
$table->string('profile_picture')->nullable()->default('image');
$table->timestamps();
$table->rememberToken();
$table->engine = 'InnoDB';
});
图像迁移:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description')->nullable()->default(null);
$table->integer('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->string('file_name');
$table->string('upvotes')->default(0);
$table->string('downvotes')->default(0);
$table->string('views')->default(0);
$table->timestamps();
$table->engine = 'InnoDB';
});
解决方案
这可能是因为您使用了不同的数据类型,尝试使数据类型相同,它应该可以工作。Int - bigInt 或字符串 Int ,请检查。
也分两步添加,也可以不签名。
否则一定是打字错误。
推荐阅读
- c# - XAML MVVM 绑定似乎已成功,但已绑定到其他一些变量
- google-cloud-functions - Firebase 云函数 - 错误:函数未正确部署。- 提供的模块无法加载
- javascript - React 跟踪点击的元素
- laravel - laravel jenssegers mongodb whereraw 正则表达式整数类型不起作用
- python - 你好社区的stackoverflow,我的问题是关于python
- swift - 为什么 Swift 在它的字典上使用线性探测?
- javascript - 在 Swift 中调用 NPM (Javascript)
- wordpress - “failed_to_connect_to_backend” - 502 网站暂时关闭
- linux - 将 Linux 文件复制到另一个位置
- javascript - 整个组件的不必要的重新渲染