首页 > 解决方案 > 在具有现有主键的表中添加自动递增 id

问题描述

我正在尝试使用其现有主键将自动递增 id 添加到现有表中

这是我的代码

表代码的初始迁移

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->string('ISBN')->index();
            $table->string('name')->index();
            $table->string('publisher');
            $table->string('level_levelName')->index();
            $table->string('provider_providerName')->index();
            $table->string('category_categoryName')->index();
            $table->text('description');
            $table->timestamps();
            $table->primary('ISBN');
            $table->foreign('provider_providerName')->references('providerName')->on('providers')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('level_levelName')->references('levelName')->on('levels')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('category_categoryName')->references('categoryName')->on('categories')->onDelete('cascade')->onUpdate('cascade');

        });
    }

将自动增量 id 添加到现有表代码

    public function up()
    {
        Schema::table('books', function (Blueprint $table) {
            $table->bigIncrements('id');
        });
    }

我想要做的是向这个现有表添加一个自动递增的 id,但它给了我这个错误

 SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary keys defined (SQL: alter table 
`books` add `id` bigint unsigned not null auto_increment primary key)

请问有人可以帮我吗?我不想删除表的主键,我只想添加另一个自动递增的 id,它不是主键,但它可以是unique key

标签: phpmysqllaravellaravel-migrations

解决方案


这不是 Laravel 错误。mysql 表中不能有两个自动增量列。

但是,您可以添加到模型中,获取数据库中字段的最大值,然后 +1 然后插入。

其他解决方案可以在这里找到


推荐阅读