【问题标题】:How to clone Laravel migration fields into another migration?如何将 Laravel 迁移字段克隆到另一个迁移中?
【发布时间】:2020-09-15 14:28:33
【问题描述】:

我有这个 Laravel 迁移结构:

class CreateWarehouseProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('warehouse_products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id')->default(0);
            $table->integer('warehouse_id');
            $table->integer('free_amount')->default(0);
            $table->integer('booked_amount')->default(0);
            // ...
            $table->timestamps();
        });
    }

    // ...
}

我需要从仓库产品创建每日备份,为此我需要创建一个与warehouse_products 完全相同的新表,并包含一个额外的备份日期字段。

是否有任何最佳做法可以做到这一点?我认为是这样的:

class CreateWarehouseProductBackupTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('warehouse_product_backups', function (Blueprint $table) {
            CreateWarehouseProductTable->cloneFieldsToHere();
            $table->date('date_of_backup');
        });
    }
}

是否有类似的好做法可以从现有迁移中克隆字段?

【问题讨论】:

  • 我不太了解这个用例。为什么不将每日导出为 CSV?
  • 因为它不是 CSV 备份,而是数据库备份,以便稍后创建有关产品数量的统计信息。在我的应用程序中,产品数量在仓库中有许多状态。我们有free_amount、booked_amount、under_shipping_amount、wait_for_shipping_amount等……20多个州……我需要创建一个每日备份,稍后创建一个产品库存量变化的图表。
  • 你也可以考虑spatie/laravel-backup
  • 但我不想从我的应用创建备份。我只想将表中的数据复制到另一个表中,对于此操作,我需要创建一个列同步的表。

标签: laravel laravel-6 laravel-migrations


【解决方案1】:

我找到了一个解决方案,我认为不优雅,但它正在工作:

class CreateWarehouseProductTable extends Migration
{
    public function up()
    {
        Schema::create('warehouse_products', function (Blueprint $table) {
            $this->setWarehouseProductColumns($table);
        });

        Schema::create('warehouse_product_backups', function (Blueprint $table) {
            $this->setWarehouseProductColumns($table);
            $table->date('date_of_backup')->nullable();
        });
    }

    public function setWarehouseProductColumns(Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('product_id')->default(0);
            $table->integer('warehouse_id');
            $table->integer('free_amount')->default(0);
            $table->integer('booked_amount')->default(0);
            // ...
            $table->timestamps();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多