mysql - 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_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 的内置关系而不是手动处理中间数据透视表。
推荐阅读
- c++ - 如何从 C++ 处理 C 库中不同大小的类型
- sql - CASE 语句仍然返回多行
- python - 使所有用户都可以访问由 pip 安装的程序 (aws cli)
- angular - 如何将对象属性绑定到 page-router-outlet 的 name 属性?
- spring-boot - Spring WebFlux WebClient 挂起并且 Mono.timeout 没有捕捉到它
- javascript - 如何将块按到主窗口底部?
- actionscript-3 - 跟踪 as3 的事件侦听器
- r - 在 r 中查找并提取超过阈值的值
- r - 在插入符号的训练函数中并行调整 xgboost 模型时出错
- firebase - 创建/更新/删除 Firebase 实时数据库规则