php - Laravel 迁移 : 2 different tables with the same blueprint/structure

标签 php mysql laravel migration

我需要 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;
});

最佳答案

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

$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/

相关文章:

php - 从原始 sql 更改为 codeigniters 事件类

php - PHP 内存泄漏工具?使用灯

mysql - 如何从 MySQL 表中删除特定行?

php - Laravel 模型中的 MySql 数据库查询问题

php - Laravel PHP fatal error : Class 'Table' not found with migrate command

php - 加载使用 SWIG 制作的 php 扩展时 undefined symbol

php - HTML5 服务器发送的事件 : empty response

php - PHP 中的 Mysql 表索引

mysql - 5.1.47 到 5.5.8 升级后 innodb 和 mysql 索引差异

jquery - 如何在 $ajax(js 文件)中使用 laravel url 和路由助手