简体   繁体   English

如何在 laravel 迁移中更改主键

[英]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然后,我进行了另一个迁移以更改adv_id列类型以准备添加外键

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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