首页 > 解决方案 > 不能约束到 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();
        });
    }

这里有什么问题?

标签: mysqldatabaselaravel

解决方案


一个可能的问题是product.category_id(外键列)和category.id(引用的主键)之间的数据类型不同。

(这只是一种可能性。问题可能是由于其他原因。)

但我们应该首先检查两列的数据类型是否完全匹配。如果它们不匹配,那么我们将无法定义 InnoDB 外键约束。

我的猜测是category.id被定义为BIGINT数据类型。

(这是一个猜测,我不是 Laravel 模式构建器的专家,但我确实看到模式构建器在屏蔽/隐藏 MySQL 表的实际 SQL 定义方面做得很好。)

(完全不清楚为什么 Laravel 需要指定外键列的数据类型。我们知道它与引用列的数据类型匹配。)


我对修复的猜测是更改此行

从:

 $table->integer('category_id')->unsigned()->nullable();

至:

 $table->bigInteger('category_id')->nullable();

推荐阅读