php - Laravel 8 迁移 "General error: 1215 Cannot add foreign key constraint"

标签 php laravel migration database-migration laravel-8

我正在尝试在 Laravel 8 上创建迁移,这是我的表格

class CreateProductVariationOrderTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_variation_order', function (Blueprint $table) {
            $table->integer('order_id')->unsigned()->index();
            $table->integer('product_variation_id')->unsigned()->index();
            $table->integer('quantity')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->foreign('product_variation_id')->references('id')->on('product_variations')->onDelete('cascade');
        });
    }
    public function down()
    {
        Schema::dropIfExists('product_variation_order');
    }
}

当我运行 php artisan migrate 时,我收到了这样的错误:SQLSTATE[HY000]: General error: 1215 Cannot addforeign keyconstraint (SQL: alter table Product_variation_order添加约束product_variation_order_order_id_foreign外键(order_id)引用orders(id)删除级联)

⚠️编辑:这是我的product_variation迁移文件。

class CreateProductVariationsTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_variations', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_id')->unsigned()->index();
            $table->string('name');
            $table->integer('price')->nullable();
            $table->integer('order')->nullable();
            $table->timestamps();

            $table->foreign('product_id')->references('id')->on('products');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('product_variations');
    }
}

最佳答案

外键必须与引用键类型相同。

在订单表中,您将 id 定义为 bigIncrements(),它是无符号大整数。

在您的product_variation_order表中,您将order_id定义为无符号整数。

所以这两个键不匹配。一般来说,您应该使用大整数,因为它允许您的数据库变得更大,并且整数和大整数之间的空间差异并不显着。

因此将 order_id 更改为无符号大整数。

$table->unsignedBigInteger('order_id')->nullable();

此外,为了保持一致性,所有键都应该是 bigIncrements()unsignedBigInteger(),这将让您以后不再头疼。

关于php - Laravel 8 迁移 "General error: 1215 Cannot add foreign key constraint",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66736682/

相关文章:

php - 如何使用 PHP 在 excel 单元格中换行?

laravel - 静态类方法的部分模拟不起作用

mysql - Laravel 4 + Blade,但 MySQL 未采用 UTF-8 编码

ruby-on-rails - Rails/postgresql 将数据从数据库迁移到新创建的数据库

ruby-on-rails - Rails Migrations 可以用来转换数据吗?

php - 使用主键和复选框使用 PDO、PHP 和 MYSQL 删除语句

php - 表单选择查询输出 - 数组

php - 使用 jquery 和 ajax 更新 <select> 选项列表

Laravel:为所有模型创建一个通用函数

node.js - 列出所有连接到 Socket.io 版本 > 1 房间的客户端