【问题标题】:Laravel Migration: 2 different tables with the same blueprint/structureLaravel 迁移:具有相同蓝图/结构的 2 个不同的表
【发布时间】:2020-01-05 02:44:39
【问题描述】:

我需要 2 个 MySQL 表,例如:historyhistory_archive 具有完全相同的结构,

history_archive 表用于从history 表中移动项目,并且在history 表中的行数更少,以便更快地查询(而不是仅仅将它们标记为在同一个表中存档)

我想过进行 2 次迁移,但是这 2 个表需要完全相同才能在它们之间移动项目,我不认为复制/粘贴每一列都是个好主意!

这里的最佳做法是什么?

我知道以下是可能的:

Schema::create('history', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    // ... extra columns 
});

// Exactly the same structure as above
Schema::create('history_archive', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    // I don't want to copy paste every column from history table here...
});

但我的问题是:我怎样才能只编写一次蓝图/构造,并将其传递给Schema::create()(并且有两个名称不同但结构相同的表)

我需要的是这样的东西(不起作用):

// Write blueprint only once
$table = new Blueprint();
$table->increments('id');
$table->unsignedInteger('user_id');
// ... extra columns 

Schema::create('history', function () use ($table) {
    $table;
});

Schema::create('history_archive', function () use ($table) {
    $table;
});

【问题讨论】:

  • 您可以在同一个迁移中创建多个表。但我不明白你的意思是“我不想在这里复制粘贴历史表中的每一列......”
  • @porloscerrosΨ 就像我说的那样,这两个表具有完全相同的列/结构,所以我的问题是如何只编写一次蓝图/构造,并将其传递给Schema::create()(和有 2 个名称不同但结构相同的表)

标签: php mysql laravel migration


【解决方案1】:

您可以在同一迁移中创建多个表。如果所有表的结构完全相同,并且您不想复制粘贴每一列,我认为您可以这样做:

$tables = ['history', 'history_archive'];
foreach($tables as $tablename) {
    Schema::create($tablename, function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        // ... extra columns 
    });
}

【讨论】:

  • 哇,我非常专注于将蓝图传递给 2 个 Schema,以至于我完全错过了这一点。聪明,工作正常,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多