php - laravel 迁移 SQLSTATE[HY000]:一般错误:1215 无法添加外键约束
问题描述
当我尝试在 laravel 中运行迁移命令时出现此错误
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
在将此问题标记为重复或否决之前,请完整阅读该问题。
我在这个网站上找到的解决方案是:
- 标记为
unsigned
我有 - 在 2 步中制作整数我有
- 架构顺序问题我提供屏幕截图以查看情况并非如此
我不确定为什么会出现该错误,这是我的代码:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug')->unique();
$table->longText('body');
$table->string('photo');
$table->text('meta_description')->nullable();
$table->text('meta_tags')->nullable();
$table->integer('user_id')->unsigned();
$table->string('publish')->default('0');
$table->string('comment')->default('0');
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
任何想法?
更新
用户架构
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('photo')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
解决方案
users
表中的主键是BigIncrements
创建一个无符号大整数列,但posts
表中的外键是整数,所以它们不是同一类型。
将外键更改为bigInteger
将修复它。
所以这:
$table->bigInteger('user_id')->unsigned();
代替:
$table->integer('user_id')->unsigned();
推荐阅读
- reactjs - 在 React / Typescript / Redux 运行时更改 Monaco 编辑器选项
- google-api - 用于 .Net 核心的服务器端应用程序的 Google 登录
- c - 假设指向同一个变量的两个指针是非法的/UB,为什么 C 编译器不能优化更改 const 指针的值?
- request - Chrome 开发工具。没有内容长度标头时如何检查请求的传出大小?
- c# - PowerBI Embed 令牌请求返回错误“提供的角色无效”
- c# - 是否可以将添加、删除和列表功能移动到单独的方法中
- java - 默认 log4j 策略
- sql - SQL 合并变量数量(母项)
- ios - SwiftUI:菜单打开时如何忽略背景上的点击?
- python - 有什么方法可以在 Python 中的 Cloud Function 中格式化我的日志吗?