Laravel:在重新播种之前重置自动增量 table
Laravel: Reset auto increment before re-seeding a table
有没有办法在播种前将自动增量设置回 1 table?
我在播种之前清空了 table,如果我在播种之前没有做 migrate:refresh
那么它会从最后一个位置继续自动递增 ID,例如 4.
Table种子:
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();
}
正在创建 table:
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();
});
试试这个:
DB::statement('SET FOREIGN_KEY_CHECKS=0');
DB::table('products')->truncate();
而不是
DB::table('products')->delete();
如果您使用 make:migration
或 make:model -m
命令创建迁移,Laravel 正在创建带有 dropIfExists()
子句的 down()
方法:
public function down()
{
Schema::dropIfExists('products');
}
因此,当您 运行 migrate:refresh
命令时,Laravel 将删除 table 并为您重新生成它。
另外,你在table中有外键,所以你需要先使用dropForeign()
:
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropForeign('products_category_id_foreign');
});
Schema::dropIfExists('products');
}
有没有办法在播种前将自动增量设置回 1 table?
我在播种之前清空了 table,如果我在播种之前没有做 migrate:refresh
那么它会从最后一个位置继续自动递增 ID,例如 4.
Table种子:
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();
}
正在创建 table:
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();
});
试试这个:
DB::statement('SET FOREIGN_KEY_CHECKS=0');
DB::table('products')->truncate();
而不是
DB::table('products')->delete();
如果您使用 make:migration
或 make:model -m
命令创建迁移,Laravel 正在创建带有 dropIfExists()
子句的 down()
方法:
public function down()
{
Schema::dropIfExists('products');
}
因此,当您 运行 migrate:refresh
命令时,Laravel 将删除 table 并为您重新生成它。
另外,你在table中有外键,所以你需要先使用dropForeign()
:
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropForeign('products_category_id_foreign');
});
Schema::dropIfExists('products');
}