简体   繁体   中英

How to take backup of DB table before truncating in a Laravel migration file?

The question has similarity with this .

Although that question seems unresolved, the comment section points out:

A true revertible migration would make a backup copy of the table visitors on up() before truncating and then copy the backup into the original on down().

Could not find any working solution for implementing the above steps.

How to take the dump of the DB table before truncating? Found some examples showing how to import from a .sql file, but that is not helpful here without first exporting the data.

The code would look something like:

class TruncateApiKeysTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // take backup of current api_keys
        // run the truncate
        if (Schema::hasTable('api_keys')) {
            Schema::table('api_keys', function(Blueprint $table) {
                $table->truncate();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
       // import data from the sql dump file
       // insert data into api_keys to revert changes
    }

Solution 1: save your existing record as seeders before truncate. Using db to seeder tool such as https://github.com/orangehill/iseed , you could call php artisan iseed my_table in CLI or Artisan::call('iseed my_table'); in php.

Solution 2: create a backup mysql db, then save the table there before truncating. Meaning you will have 02 mysql connection:

  • current_db
  • backup_db

You can easily handle multiple DB with laravel .

You could copy the table using CREATE TABLE blah_backup LIKE blah;

public function up()
{
    DB::statement('CREATE TABLE foo_backup LIKE foo;');
    DB::statement('
    INSERT foo_backup
    SELECT *
    FROM foo;');

    Schema::table('foo', function (Blueprint $table){
        //Change the table in a way that could lose data
    }
}
public function down()
{
    // recover the backup
    Schema::drop('foo');

    DB::statement('CREATE TABLE foo LIKE foo_backup;');
    DB::statement('
    INSERT foo
    SELECT *
    FROM foo_backup;');

    Schema::drop('foo_backup');
}

You do have to worry about cleaning up the backup eventually but that seems like a minor detail to me for the convenience of the migration and a property rollback where you don't lose data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM