【问题标题】:Laravel General error: 1215 Cannot add foreign key constraintLaravel 一般错误:1215 无法添加外键约束
【发布时间】:2020-06-12 20:49:40
【问题描述】:

我有两个模型:

类别

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title',10);
        $table->timestamps();
    });
}

产品

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('category_id')->index('category_id');
        $table->string('title', 20);
        $table->text('description');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });
}

当我运行 php artisan make:migrate 时,我收到此错误:

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1215 无法添加外键约束(SQL:alter table products 添加约束products_category_id_foreign外键 (category_id) 引用categories (id))

我做错了什么?

【问题讨论】:

  • 您试图在 signed 大整数和 unsigned 大整数之间放置一个外键。使它们都未签名....
  • 您的代码是正确的。你没有任何错误
  • 不,这是不可能的,因为如果我用 $table->foreign('category_id')->references('id')->on('categories');表用户 id 没有问题是 bigIncrement

标签: php mysql laravel migration


【解决方案1】:

引用列和被引用列必须具有相同的数据类型,如the documentation 中所述:

外键和引用键中的对应列必须具有相似的数据类型。 整数类型的大小和符号必须相同。字符串类型的长度不必相同。对于非二进制(字符)字符串列,字符集和排序规则必须相同。

您应该将两列都设为无符号,或者都设为有符号。无符号似乎与递增的密钥更相关:

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->unsignedBigInteger('id'); # changed to unsigned
        $table->string('title',10);
        $table->timestamps();
    });
}


public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('category_id')->index('category_id');
        $table->string('title', 20);
        $table->text('description');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });
}

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 2019-09-08
    • 2021-03-29
    • 2018-07-29
    • 2018-07-29
    • 1970-01-01
    • 2019-08-02
    • 2021-07-03
    相关资源
    最近更新 更多