我需要 2 个 MySQL 表,例如:history
、history_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;
});
最佳答案
您可以在同一迁移中创建多个表。如果所有表都具有完全相同的结构,并且您不想复制粘贴每一列,我认为您可以这样做:
$tables = ['history', 'history_archive'];
foreach($tables as $tablename) {
Schema::create($tablename, function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
// ... extra columns
});
}
关于php - Laravel 迁移 : 2 different tables with the same blueprint/structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750563/