首页 > 解决方案 > Laravel 5.8:总是给出多个主键语法或访问冲突错误

问题描述

我用复合主键创建了迁移文件,但总是报错

语法错误或访问冲突:1068 定义了多个主键(sql:alter table 'table_currency' 添加主键 table_currency_code_user_id_primary('code', 'user_id'))

 Schema::create('table_currency', function (Blueprint $table) {
        $table->string('code', 3);
        $table->bigIncrements('user_id');
        $table->string('default', 3);
        $table->enum('is_active', ['0','1'])->default('0')->comment('0: Inactive, 1: Active');
        $table->timestamps();
        $table->primary(['code', 'user_id']);
    });

我不明白为什么我得到这个错误?提前谢谢。

标签: eloquentlaravel-5.8

解决方案


如果要创建复合主键,则['user_id', 'code']需要删除increments列上附加的主键。您可以使用以下代码执行此操作:

 Schema::create('table_currency', function (Blueprint $table) {
    $table->bigIncrements('user_id'); // Has a primary key
    $table->dropPrimary('table_currency_user_id_primary'); // Remove the primary key from the increments column
    $table->primary(['code', 'user_id']); // Set your composite primary key
    $table->string('code', 3);
    $table->string('default', 3);
    $table->enum('is_active', ['0','1'])->default('0')->comment('0: Inactive, 1: Active');
    $table->timestamps();
    });

推荐阅读