php - Laravel 迁移:具有相同蓝图/结构的 2 个不同的表
问题描述
我需要 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
});
}
推荐阅读
- javascript - Problem with Divi stylesheet - remove css on element placed on element by style sheet
- mysql - How can I find the number of orders for every distinct customer?
- git - git push 提交到公关和讨论
- matplotlib - CUDA 加速 Matplotlib
- bash - 循环遍历使用参数指定的目录中的文件
- java - 使用 Java - JSch 通过 SSH 连接到服务器并发出 shell 命令
- elasticsearch - 在 JanusGraph 0.2.1 配置弹性搜索身份验证
- c - C: realloc 对它释放的内存做了什么?
- python-3.x - 切片 H20 框架
- node.js - 如何部署node js web服务器?