Laravel迁移中如何让ID从某个数字开始自增

How to let ID autoincrement start from certain number in Laravel Migration

我想写一个Laravel迁移自增ID作为主键。我想用另一个值而不是 1 开始此 ID。我该怎么做?

迁移up()函数:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('phone');
        $table->rememberToken();
        $table->timestamps();
    });
}

添加一条id为(所需id为-1)的记录,然后删除。

如果您添加一条 ID 为 999 的记录,然后将其删除,下一条记录的 ID 将为 1000。您还可以在数据库中使用 SQL 身份

您可以使用 2 种方法

按声明 DB::statement("ALTER TABLE your_table_here SET AUTO_INCREMENT = 9999;");

通过插入行和删除行。

DB::table('your_table_here ')->insert(['id' => 99999, ... ,'column' => 'value']);
DB::table('your_table_here ')->where('id', 99999)->delete();

希望对您有所帮助

试试这个?

$table->increments('id')->start_from(10000);

创建迁移后,只需转到您的 Mysql 数据库并输入此查询

ALTER TABLE users AUTO_INCREMENT = 1000;

从 Laravel 8.x 开始,您现在可以在迁移中使用它:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id()->startingValue(1200);
    });
}

来源:https://laravel-news.com/laravel-auto-increment

如果您希望 table 中的 第一个 ID 例如 10001.

如果您正在使用 Laravel 8.x

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id')->from(10001);
        .
        .
        $table->timestamps();
    });
}