Laravel:在重新播种表格之前重置自动增量

rit*_*its 2 php mysql laravel laravel-5.3

有没有办法在播种表之前将自动增量设置回1?

我在播种之前清空了桌子,如果我migrate:refresh在播种之前没有做,那么它继续从最后一个位置自动增加ID,例如4.

表种子:

public function run()
{
    DB::table('products')->delete();
    // Product table seeder
    $product = new \App\Product([
        'category_id' => 1,
        'image_path' => '/images/products/1/000001.jpg',
        'title' => 'test',
    ]);
    $product->save();
}
Run Code Online (Sandbox Code Playgroud)

创建表:

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('categories');
    $table->string('image_path');
    $table->string('title');
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

Rim*_*han 12

试试这个:

DB::statement('SET FOREIGN_KEY_CHECKS=0');

DB::table('products')->truncate();
Run Code Online (Sandbox Code Playgroud)

代替

DB::table('products')->delete();
Run Code Online (Sandbox Code Playgroud)

  • 在开头添加`DB :: statement('SET FOREIGN_KEY_CHECKS = 0;');`并在种子末尾添加`DB :: statement('SET FOREIGN_KEY_CHECKS = 1;');`并更改`DB: :table('products') - > delete();`to`DB :: table('products') - > truncate();`做到了. (4认同)