bitinn
bitinn

Reputation: 9338

Data migration from old table into new table, with Laravel 4

Is it possible to copy data from old table into new table instead of rename? We are planning a major database schema upgrade and would like to preserve current data tables, so the migration down() can be as simple as dropping newly created tables.

we realize this breaks backward compatibility as migrate:rollback doesn't really rollback any new data into previous state; but enabling such thing will be very costly due to the scale of schema update, we are content with a simple 1-way migration, as long as it preserves old tables.

Can this be done within Laravel's migration and schema alone?

Upvotes: 3

Views: 5279

Answers (4)

Broshi
Broshi

Reputation: 3592

Not sure it helps but i wrote a small class that helps copying data between two databases with totally different structure according to rules you provide on a xml file, see https://github.com/Binternet/redb So maybe you can fire this up when you finish the last migration

Upvotes: 0

bitinn
bitinn

Reputation: 9338

Thanks to suggestion from @TonyArra and @Fractaliste, we now do something like following, this allow us to test run migration and rollback without worrying about data lost.

use Illuminate\Database\Migrations\Migration;

use MyNewModel;

class DataConvert extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        foreach(MyOldModel::all() as $item)
        {
            MyNewModel::create(array(...));
        }

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        MyNewModel::truncate();
    }

}

Upvotes: 7

Tony Arra
Tony Arra

Reputation: 11099

As far as I know, there's no copy function in Laravel to do this, but it's fairly easy with models. For example, if you wanted to move data from the table users to newusers, you could add the following to the NewusersTableSeeder run function:

$users = User::all()->toArray();
foreach ($users as $user) {
    $user['newField'] = "data";
    Newuser::create($user);
}

(recommend that this be done in the seeder, as you should already have Eloquent::unguard(); in DatabaseSeeder.php)

Upvotes: 2

Fractaliste
Fractaliste

Reputation: 5957

Into the down() function and just before dropping your tables, I think you can perform an export of your data.

The basic use of migration is to create/drop tables. But nothing prevents you to make a more complex one. And the artisan tool provides access to any Laravel's functionality (except network one's like Input or Cookies I think)

Upvotes: 1

Related Questions