php - 外键约束的格式不正确。你能帮助我吗?

标签 php mysql laravel laravel-5 migration

你能帮帮我吗?

我用的是MySQL。

我做

php artisan migrate

但是错误

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table learn.products (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table products add constraint products_category_id_foreign foreign key (category_id) references categories (id))

类别迁移:

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

产品迁移:

    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');
    });

最佳答案

替换:$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

Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

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

$table->increments(): Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.

$table->unsignedBigInteger(): UNSIGNED BIGINT equivalent column.


所以在你的情况下:

$table->unsignedBigInteger('category_id'); => UNSIGNED BIGINT

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

它们不匹配。

关于php - 外键约束的格式不正确。你能帮助我吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57421072/

相关文章:

php - MySQL 更新功能不工作

mysql - 对数据进行非规范化

Laravel 如何在 session 中存储额外的数据/值 Laravel

php - 消息为 'Call to undefined method Illuminate\Database\Query\Builder::toArray()' 的 BadMethodCallException

php - 检查远程主机上的 mysql 状态

php - Yii2 db mysql 连接抛出 ssh 端口 33060

php mysql 多次更新什么也不做

java - 列结果不符合预期

php - 为什么如果我不在表单末尾放置 {{csrf_field()}} (在 Laravel 5 View 中),我会收到 TokenMismatchException?

php - 使用 Eloquent/Laravel 5.3 使用 save () 更新我的表是更新所有行而不是一个