【问题标题】:What should I put in my down function when truncate a table in Laravel migration?在 Laravel 迁移中截断表时,我应该在 down 函数中添加什么?
【发布时间】:2016-03-25 13:29:14
【问题描述】:

我正在尝试编写一个迁移脚本来截断我的 vistors 表。 我们通常将up函数的revert放在down函数中。

但是在这种情况下,它是一个 truncate,我应该在我的 down 函数中添加什么?

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TruncateVisitorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       DB::table('visitors')->truncate();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // what should I put here ? 
    }
}

【问题讨论】:

  • 你放什么取决于你想要什么?如果您从表中截断了一些固定数据,则播种/插入数据。如果它有动态数据(来自您的应用程序),我想知道您为什么要截断它?
  • 真正的可恢复迁移会在截断之前对up() 上的表访问者进行备份,然后将备份复制到down() 上的原始文件中。对于您的需求,这可能是不必要的。
  • 感谢两位分享您的建议。 :)
  • @JoshJ 有没有办法实现你提到的步骤?因为我在 Laravel 文档中找不到任何内容

标签: php laravel laravel-5


【解决方案1】:

这是我使用的一个例子:

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        //
    });

    Schema::create('cats', function(Blueprint $table)
    {
        //
    });

    Schema::create('items', function(Blueprint $table)
    {
        //
    });
}

public function down()
{
    $tables = [
        'users',
        'cats',
        'items'
    ];

    foreach($tables as $table) Schema::drop($table);
}

您可以在播种机的开头使用truncate

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 2021-06-21
    • 2021-06-09
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2018-07-18
    • 2021-09-28
    • 2017-10-08
    相关资源
    最近更新 更多