首页 > 解决方案 > Laravel 迁移:具有相同蓝图/结构的 2 个不同的表

问题描述

我需要 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()(并且有 2 个名称不同但结构相同的表)

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

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

标签: phpmysqllaravelmigration

解决方案


您可以在同一迁移中创建许多表。如果所有表都具有完全相同的结构,并且您不想复制粘贴每一列,我认为您可以执行以下操作:

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

推荐阅读