使用现有主键在 table 中添加自动递增 id

add auto incrementing id in a table with existing primary key

我正在尝试将自动递增 ID 添加到现有 table 及其现有主键

这是我的代码

table 代码的初始迁移

    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 添加到现有 table 代码

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

我想做的是向这个现有的 table 添加一个自动递增的 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)

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

您不能使用 bigIncrements,因为那样会尝试将其创建为主键。您可以试试这个:

$table->bigInteger('id', true, true)->index();

根据 bigInteger 的定义(public function bigInteger($column, $autoIncrement = false, $unsigned = false)) 第二个值用于自动递增,第三个值是 signed/unsigned。从 Mysql Innodb: Autoincrement non-Primary Key 开始,自动递增键必须被索引。

这不是 Laravel 错误。 mysql table.

中不能有两个自动递增列

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

可以找到其他解决方案here