vendredi 28 septembre 2018

Process data in migration

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.

  1. Create new table user_roles
  2. Create user_role entities with data from user->role
  3. Remove column role from user table

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');
    });
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zBsBoz
via IFTTT

Aucun commentaire:

Enregistrer un commentaire