Laravel Migration: 2 Different Tables With The Same Blueprint/structure
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;
});
Answer
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
});
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?