Laravel 5.8 : Always gives multiple primary key syntax or access violation error

221 Views Asked by At

I have created migration file with composite primary key but always gives an error

syntax error or access violation : 1068 multiple primary key defined (sql : alter table 'table_currency' add primary key 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']);
    });

I don't get it why I got this error? Thanx in advance.

1

There are 1 best solutions below

0
Alexandre Gérault On

If you want to make a composite primary key on ['user_id', 'code'] you need to remove the primary attached on your increments column. You can do this with this code:

 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();
    });