我的问题
我正在使用 Laravel 构建我的第一个 api,并且在尝试运行时遇到多个主键定义错误
php artisan migrate
我不明白我是如何定义多个主键的。每次运行迁移时,我都会遇到这些错误 .
我的故障排除
我想因为
autoIncrementing()
只能用于主键,也许将其定义为主键,所以我将 $table->increments('bus_id')->autoIncrement()->primary();
更改为 $table->increments('bus_id')->autoIncrement();
和 $table->increments('bus_id')->autoIncrement();
每次我尝试运行迁移时,我都会删除数据库并重新创建它,然后尝试再次运行迁移(因此每次都是一个新数据库,没有损坏的数据),但仍然没有任何作用。
我检查了上面错误代码图片中提到的 Connection.php,但没有看到与任何主键相关的任何内容。
我的问题
我的代码如下,有人可以帮助我理解如何制作双主键吗?
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePurchaseHistoryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('purchase_history', function (Blueprint $table) {
$table->increments('pur_id', 11);
$table->string('pur_item', 255);
$table->dateTimeTz('pur_date');
$table->string('bus_name', 50);
$table->double('pur_amount', 10, 2);
$table->double('cashback_amount', 10, 2);
$table->integer('bus_id', 11);
$table->foreign('bus_id')->references('bus_id')->on('business');
$table->timestamps();
$table->rememberToken();
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('purchase_history');
}
}
请注意,这里关于堆栈溢出也有类似的问题,我也尝试过他们的解决方案,但没有成功 编辑后我仍然收到此错误:
在 Connection.php 第 664 行:
SQLSTATE[42000]:语法错误或访问冲突:1075 不正确的表定义;只能有一个自动列 mn 并且必须将其定义为键(SQL:create table(purchase_history
int unsigned not null auto_incre ment 主键,pur_id
varchar(255) 不为空,pur_item
日期时间不为空,pur_date
varchar(50) 不为空,bus_name
double(10, 2) 不为空,pur_amount
double(10, 2) 不为空,cashback_amount
int 不为空 auto_increment 主键、bus_id
时间戳为空、created_at
时间戳为空、updated_at
varchar(100) null) 默认 字符集 utf8mb4 整理 utf8mb4_unicode_ci 引擎 = InnoDB)remember_token
运行 php artisan migrate 后:刷新
试试这些
increments
bus_id
是外键,则在添加 unsigned
之前添加
references
category
已在 purchase_history
表和类别表 auto-increment
字段为 bus_id
$table->increments('pur_id');
$table->integer('bus_id')->unsigned();
$table->foreign('bus_id')->references('bus_id')->on('category');
^ make sure category table auto increment field value is bus_id
仅供参考:如果我绘制表格,我将
id
设置为自动增量字段上的名称。因为没有混乱。
从您的 pk 定义中删除
autoincrements
和 primary
。
$table->increments('bus_id');
文档中的定义:
自动递增 UNSIGNED INTEGER(主键)等效列。
https://laravel.com/docs/5.5/migrations#columns
编辑:
increments
方法仅采用一个参数:
$table->increments('pur_id');
https://laravel.com/api/5.3/Illuminate/Database/Schema/Blueprint.html#method_increments
编辑
问题是
bus_id
,它也以某种方式被设置为主键。从例外情况来看:
`bus_id` int not null auto_increment primary key,