mysql - 不能约束到 Laravel 和 MySql 上的关联表
问题描述
我正在使用 MYSQL v5.7 和 Laravel v5.6,我在产品表上添加了外键。
但是出现这样的错误。
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `product` add constraint `product_category_id_foreign` foreign key (`category_id`) references `category` (`id`) on delete cascade)
这是我的产品表
public function up()
{
Schema::create('product', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned()->nullable();
$table->integer('admin_id')->unsigned()->nullable();
$table->string('name');
$table->string('description');
$table->integer('price');
$table->binary('image')->nullable(false)->change();
$table->timestamps();
});
Schema::table('product', function($table){
$table->foreign('category_id')->references('id')->on('category')->onDelete('cascade');
$table->foreign('admin_id')->references('id')->on('admin')->onDelete('cascade');
});
}
这是我的类别表
public function up()
{
Schema::create('category', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
这里有什么问题?
解决方案
一个可能的问题是product.category_id
(外键列)和category.id
(引用的主键)之间的数据类型不同。
(这只是一种可能性。问题可能是由于其他原因。)
但我们应该首先检查两列的数据类型是否完全匹配。如果它们不匹配,那么我们将无法定义 InnoDB 外键约束。
我的猜测是category.id
被定义为BIGINT
数据类型。
(这是一个猜测,我不是 Laravel 模式构建器的专家,但我确实看到模式构建器在屏蔽/隐藏 MySQL 表的实际 SQL 定义方面做得很好。)
(完全不清楚为什么 Laravel 需要指定外键列的数据类型。我们知道它与引用列的数据类型匹配。)
我对修复的猜测是更改此行
从:
$table->integer('category_id')->unsigned()->nullable();
至:
$table->bigInteger('category_id')->nullable();
推荐阅读
- bots - Telegram 中有多个机器人管理员
- amazon-web-services - AWS EC2 用户数据创建 SH 脚本
- typescript - 模式匹配 switch 语句
- javascript - 一些量角器测试被跳过
- mysql - 查询某个特定客户在去年下的总订单在不存在订单时检索重复日期
- python - 正则表达式匹配任何数字,除了包含重复零的数字
- c++ - 从 Boost 库编译函数时出现问题
- javascript - 如果有人提交空表单,我想返回“警报”框
- cmake - cmake 中的 .lst 文件生成
- python - RuntimeError:烧瓶中的线程中没有当前事件循环?