2016-11-20 61 views
1

在播種表之前是否有辦法將自動增量設置回1?Laravel:在重新播種表前重置自動增量

我空表播種前,如果我沒有播種它,然後才做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(); 
} 

創建表:

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(); 
}); 

回答

5

試試這個:

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

DB::table('products')->truncate(); 

而不是

DB::table('products')->delete(); 
+3

添加'DB ::聲明( 'SET FOREIGN_KEY_CHECKS = 0;');'開頭和增加'DB :: statement('SET FOREIGN_KEY_CHECKS = 1;');'在種子末尾,改變DB :: table('products') - > delete();'DB∷table('產品') - > truncate();'做到了。 – Rudolph

+0

你的問題只是要求重新播種表格@Rimon Khan認爲這隻適用於PRIMARY KEY。總的來說,由於滿足了這個問題,因此提出了答案。 – Ronald

1

如果您使用make:migrationmake:model -m命令來創建一個遷移,Laravel創造down()dropIfExists()條款:

public function down() 
{ 
    Schema::dropIfExists('products'); 
} 

所以,當你運行migrate:refresh命令, Laravel會放下桌子,並會爲你重新制作。

此外,你必須在表的外鍵,所以你需要使用dropForeign()第一:

public function down() 
{ 
    Schema::table('products', function (Blueprint $table) { 
     $table->dropForeign('products_category_id_foreign'); 
    }); 

    Schema::dropIfExists('products'); 
} 
+1

「Laravel」的方式,絕對是這樣做的。 – Ohgodwhy