Reputation: 999
I need 2 MySQL tables such as: history
, history_archive
to have the exact same structure,
The history_archive
table is used to move items from history
table and having fewer rows there for faster queries in history
table (instead of just marking them as Archived in the same table)
I thought of having 2 migrations, but these 2 tables need to be exactly same to move items between them and I don't tthink copy/paste of every column is a good idea!
What is the best practice here?
I know the following is possible:
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...
});
But my question is: How can I write the blueprint/construction only once, and pass it to both Schema::create()
(and have 2 tables with different names, but same structure)
What I need is something like this (which doesn't work):
// 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;
});
Upvotes: 1
Views: 327
Reputation: 5078
You can create many tables in same migration. If all the tables have exactly the same structure, and you don't want to copy paste every column, I think you can do something like this:
$tables = ['history', 'history_archive'];
foreach($tables as $tablename) {
Schema::create($tablename, function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
// ... extra columns
});
}
Upvotes: 4