【发布时间】:2020-01-01 00:41:12
【问题描述】:
<?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_product (order_id bigint unsigned not null auto_increment 主键,product_id bigint unsigned not null auto_increment 主键) 默认字符集 utf8mb4 collate
'utf8mb4_unicode_ci')
What is wrong with my code? :(
【问题讨论】:
-
我认为
bigIncrements()也会使主键成为主键,并且您不能在同一个表中拥有多个主键。虽然错误似乎与外键有关,但我不是 100% 确定。 -
bigIncrements()使自动递增UNSIGNED BIGINT(主键)等效列。 MySQL 不允许两个主键存在于一个表中。我假设您需要使用$table->bigInteger('product_id');,这应该是一个BIGINT数据类型。 -
把两个
bigIncrements改成unsignedBigInteger。您正在尝试在数据透视表中创建两个自动增量列。 -
我将 bigIncrements 更改为 unsignedBigInteger 并且它可以工作。非常感谢! :)