2016-11-20 87 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