思路
迁移也是运行数据库DDL语句,那么只要在Laravel迁移的语句后面添加自定义DDL语句设置自动递增初始值就好了。
引用DB
use Illuminate\Support\Facades\DB;
MySQL
以修改users表为例,设置自动递增初始值为例1000
DB::statement('ALTER TABLE users AUTO_INCREMENT=1000');
PostgreSQL
修改users表的序列,设置自动递增初始值为例1000。
DB::statement('alter sequence users_id_seq restart with 1000');
其他
如果在配置里面设置了表前缀,需要手动添加表前缀。
参考
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
$prefix = DB::getConfig('prefix');
$driver = DB::getConfig('driver');
if ('mysql' == $driver) {
DB::statement("ALTER TABLE {$prefix}users AUTO_INCREMENT=1000");
}
if ('pgsql' == $driver) {
DB::statement("alter sequence {$prefix}users_id_seq restart with 1000");
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}