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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40702739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:46:47  来源:igfitidea点击:

Laravel: Reset auto increment before re-seeding a table

phpmysqllaravellaravel-5.3

提问by rits

Is there a way to set auto increment back to 1 before seeding a table?

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

I empty the table before seeding it and if I didn't do migrate:refreshbefore seeding it then it continues the auto increment of the ID from the last position, e.g., 4.

我在播种之前清空表格,如果我migrate:refresh在播种之前没有这样做,那么它会从最后一个位置继续自动增加 ID,例如 4。

Table seed:

表种子:

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

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

回答by Rimon Khan

Try this:

尝试这个:

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

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

Instead of

代替

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

回答by Alexey Mezenin

If you're using make:migrationor make:model -mcommands to create a migration, Laravel is creating down()method with dropIfExists()clause:

如果您使用make:migrationmake:model -m命令来创建迁移,Laravel 将down()使用dropIfExists()子句创建方法:

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

So when you run migrate:refreshcommand, Laravel will drop the table and will recraete it for you.

因此,当您运行migrate:refresh命令时,Laravel 会删除该表并为您重新创建它。

Also, you have foreign keys in the table, so you need to use dropForeign()first:

此外,您在表中有外键,因此您需要先使用dropForeign()

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

    Schema::dropIfExists('products');
}