【问题标题】:How to let ID autoincrement start from certain number in Laravel Migration如何让 Laravel Migration 中的 ID 自动递增从某个数字开始
【发布时间】:2020-05-19 08:08:51
【问题描述】:

我想写一个 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();
    });
}

【问题讨论】:

  • 我认为没有一种优雅的方法可以做到这一点。您可能需要通过DB::statement(..) 运行原始数据库语句并使用stackoverflow.com/questions/1485668/… 的解决方案之一

标签: laravel eloquent database-migration laravel-migrations


【解决方案1】:

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

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

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

【讨论】:

    【解决方案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();
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      如果您希望表中的第一个 ID 为例如 10001

      如果您使用的是 Laravel 8.x

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

      【讨论】:

        【解决方案4】:

        添加一条id为(期望id为-1)的记录,然后删除它。

        如果您添加一条 id 为 999 的记录,然后将其删除,则下一条记录的 id 为 1000。您也可以在数据库上使用 SQL 标识

        【讨论】:

        • 那么初始值是多少?
        • 如果你添加一条 id 为 999 的记录,然后删除它,下一条记录的 id 为 1000。你也可以在你的数据库上使用 SQL 身份。
        【解决方案5】:

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

        ALTER TABLE users AUTO_INCREMENT = 1000;
        

        【讨论】:

          【解决方案6】:

          试试这个?

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

          【讨论】:

          猜你喜欢
          • 2013-01-06
          • 1970-01-01
          • 2012-05-31
          • 2017-11-03
          • 2011-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-20
          相关资源
          最近更新 更多