【问题标题】:Foreign key constraint is incorrectly formed. Can you help me?外键约束的格式不正确。你能帮助我吗?
【发布时间】:2019-12-16 15:57:55
【问题描述】:

你能帮帮我吗?

我使用 MySQL。

我做

php artisan migrate

但是错误

Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1005 无法创建表learn.products (errno: 150 "外键 约束格式不正确”)(SQL:alter table products add 约束products_category_id_foreign外键(category_id) 参考categories (id))

Categories迁移:

        Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 50)->unique();
        $table->timestamps();
        $table->softDeletes();
    });

Products迁移:

    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 150)->unique();
        $table->unsignedBigInteger('category_id');
        $table->string('image', 255);
        $table->boolean('sale')->default(false);
        $table->text('description');
        $table->timestamps();
        $table->softDeletes();
        $table->foreign('category_id')->references('id')->on('categories');
    });

【问题讨论】:

标签: php mysql laravel laravel-5 migration


【解决方案1】:

替换:$table->unsignedBigInteger('category_id');

与:$table->integer('category_id')->unsigned();

替换:$table->increments('id');

与:$table->bigIncrements('id');

在两个表中(但至少在您的类别表中)。


为什么?:

来自 MySQL 文档:https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

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

来自 Laravel 文档:https://laravel.com/docs/5.8/migrations#columns

$table->increments():自动递增 UNSIGNED INTEGER(主键)等效列。

$table->unsignedBigInteger(): UNSIGNED BIGINT 等效列。


所以在你的情况下:

$table->unsignedBigInteger('category_id'); => 无符号大整数

$table->increments('id'); => 无符号整数。

它们不匹配。

【讨论】:

  • 非常感谢。非常描述性的答案。
猜你喜欢
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2021-11-07
  • 2018-09-04
  • 2017-10-03
  • 2019-07-25
  • 1970-01-01
  • 2017-10-04
相关资源
最近更新 更多