Reputation: 7777
I'm normalizing a table by removing a column and breaking it out in another table. Before the column is removed I need to create new entities based on the data from this column.
This all need to be done with one single deploy and migration command. So the flow need to be like this.
What is the best praxis for doing this? Should I run some data processing code in the actual migration?
Is this kosher or should I just write a command that will do the data processing and then delete the column from this command. That feels a bit counter intuitive since this will not happen automatically if the application would be deployed fresh on a new server (since the column then is not removed in a migration)
Here's a mockup of what I want to do.
public function up()
{
Schema::create('user_roles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->integer('organisation_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('role_id')
->references('id')->on('roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('organisation_id')
->references('id')->on('organisations')
->onDelete('cascade')
->onUpdate('cascade');
});
// MOCKUP CODE FOR creating user_roles
$users = User::all();
foreach ($users as $user) {
$userRole = new UserRole();
$userRole->user_id = $user->id;
$userRole->role_id = $user->role;
$userRole->organisation_id = $user->getOrganisation();
$userRole->save();
}
Schema::table('users', function($table) {
$table->dropColumn('role');
});
}
Upvotes: 0
Views: 87
Reputation: 364
First, Users::all()
will kill the process if there are several thousand of users
.
I would suggest not to do any model
or data-manipulations in migrations. what will happen to you migrations if you will drop some of your models in the future?
And if your project is already working on production, then I would do this:
migration
to create roles
tableuser
model to save roles
in to places (if the column exists, then save here, and also save to roles_table
), 'couse while you run your commands there can be new registrationsartisan
command for changing the data (moving the relationship to another table)migration
to drop the old columnuser
model (that saves roles
in two places) Upvotes: 1