![](/img/trans.png)
[英]Laravel Incorrect table definition; there can be only one auto column and it must be defined as a key
[英]Laravel foreign_key Incorrect table definition; there can be only one auto column and it must be defined as a 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_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? :(
将第一行保留为$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的内置关系来代替处理中间数据透视表。
在进行迁移时,您试图在同一张表中创建两个 主键 ,这就是您得到的错误。
当您将字段声明为bigIncrements
您要laravel创建一个auto incrementing primary key
; 您在同一表中有两个此声明,这是不可能的 。
如果不想创建一个代表中间表order_product
的Model
,那么看来您想要创建一个pivot
表实际上并不需要主键 。
要消除该错误,您必须对两个前键使用unsignedBigInteger
,因为它们所引用的字段( orders
和products
表的id
列)是unsigned bigintegers
即:
public function up()
{
Schema::create('order_product', function (Blueprint $table) {
$table->unsignedBigInteger('order_id');
$table->foreign('order_id')->references('id')->on('orders');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')->on('products');
});
}
如果要在两个前键上使用composite primary key
,可以在迁移过程中编写以下代码:
$table->primary(['order_id', 'product_id']);
此行还确保您在表中不会出现重复的行( order_id
, product_id
)。 声明composite unique index
可以具有相同的效果:
$table->unique(['order_id', 'product_id']);
如果您想要一个 primary key
,则可以添加一个id
列,只需将此行写入上面的迁移中即可:
$table->bigIncrements('id');
但这仅在您需要中间表Model时才真正有用。
顺便说一句,除了bigIncrements
的错误外,用于数据透视表和字段的命名约定已经很完美了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.