简体   繁体   中英

How to change primary key in laravel migration

I'm trying to change the primary key on a table so I can use an other column as foreign key too.

Here's the migration for the creation

public function up()
{
   Schema::create('blacklists', function (Blueprint $table) {
        $table->id();
        $table->integer('adv_id')->default(0);
        // ...other columns
   });
}

Then, I've made an other migration to change the adv_id column type in order to prepare the addition of a foreign key

public function up()
{
    Schema::table('blacklists', function(Blueprint $table){
         $table->integer('adv_id')->unsigned()->change();
    });
}

Here's where I'm stocked

public function up()
{
     Schema::table('blacklists', function(Blueprint $table) {
         $table->dropPrimary('id');
         $table->integer('adv_id')->primary()->change();
     });
}

When I run the last migration, I got this error message

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: alter table `blacklists` drop primary key)

You can try this because at a time only one auto-increment allow.

public function up()
{
 Schema::table('blacklists', function (Blueprint $table) {
    $table->dropPrimary('id');
    $table->integer('adv_id')->unsigned()->change();
 });
}

this work for me

public function up()
{
 Schema::table('blacklists', function (Blueprint $table) {
   $table->dropPrimary();
   $table->unsignedInteger('id')->change();
   $table->dropColumn('id');
   $table->uuid()->primary()->unique()->index()->first();
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM