首页 > 解决方案 > Laravel foreign_key 表定义不正确;只能有一个自动列,并且必须将其定义为键

问题描述

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrderProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_product', function (Blueprint $table) {
            $table->bigIncrements('order_id');
            $table->foreign('order_id')->references('id')->on('orders');
            $table->bigIncrements('product_id');
            $table->foreign('product_id')->references('id')->on('products');
        });
    }

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


I expected to create a pivot table, but when I run the "php artisan migrate" it give me this: 

    SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key

(SQL:创建表order_productorder_idbigint unsigned not null auto_increment 主键,product_idbigint unsigned not null auto_increment 主键)默认字符集 utf8mb4 collat​​e 'utf8mb4_unicode_ci')

What is wrong with my code? :(

标签: mysqllaravel

解决方案


将第一行保留为$table->bigIncrements('id')->unsigned(); 其余行,bigIncrements改为bigInteger()改为。

public function up()
{
    Schema::create('order_product', function (Blueprint $table) {
        $table->bigIncrements('id')->unsigned();
        $table->bigInteger('order_id')->unsigned();
        $table->foreign('order_id')->references('id')->on('orders');
        $table->bigInteger('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products');
    });
}

更好的是,您可以使用Eloquent 的内置关系而不是手动处理中间数据透视表。


推荐阅读