在迁移层5.1中设置自动增量字段从1000开始

问题描述 投票:21回答:4

我需要在用户表中从1000开始我的ID,我怎么能为此创建迁移。

我目前的迁移是:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id'); // how can I start this from 1000
        $table->integer('qualification_id')->nullable();
        $table->integer('experience_id')->nullable();
    });
}
php mysql migration laravel-5.1
4个回答
26
投票

它应该是这样的(未经测试)。

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class MyTableMigration extends Migration {

     /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $statement = "ALTER TABLE MY_TABLE AUTO_INCREMENT = 111111;";
        DB::unprepared($statement);
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
    }
}

更新

//Your migrations here:
Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id')->unsigned();
    $table->integer('qualification_id')->nullable();
    $table->integer('experience_id')->nullable();
});

//then set autoincrement to 1000
//after creating the table
DB::update("ALTER TABLE users AUTO_INCREMENT = 1000;");

5
投票

大多数表使用从下一个最大整数递增的增量。

可以始终插入一个整数,该整数高于当前的自动增量索引。然后,自动增量指数将自动跟随新值+1。

所以,如果你有一个新建的表,你当前的索引是0,下一个键将是0 + 1 = 1。

我们想要的是一个从1000开始的主键,所以我们要做的是插入一个id值为999的记录,这样下一个插入就会变成1000。

在代码中:

 $startId = 1000;

 DB::table('users')->insert(['id'=> $startId - 1]);
 DB::table('users')->where('id',$startId - 1)->delete();

现在你有一个空表,下一个插入ID应该是1000。

请注意,如果您有值为种子值<startId的表的种子,则需要在执行这些语句之前执行此操作。否则,数据库将抛出约束违规错误。

这应该与数据库无关,但如果有一个数据库不遵循这个自动增量规则,我很乐意听到它。


4
投票

从Laravel 5.5迁移到创建表并设置其自动增量值

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('qualification_id')->nullable();
        $table->integer('experience_id')->nullable();
    });

    // Here's the magic
    \DB::statement('ALTER TABLE table_name AUTO_INCREMENT = 1000;');
}

DB::statement()可用于执行您需要的任何单个SQL语句。


-4
投票

Prashant的方法没有问题。但正如前面所说,不要将use DB;放在文件的顶部。

enter image description here

以下是php artisan migrate之后的结果

And here are the results

© www.soinside.com 2019 - 2024. All rights reserved.