Laravel: how to copy data from one connection to one other?

Viewed 113

I've a mysql connection and a pgsql (postgres, set as default) connection.

I must read all rows from a table from mysql and then save all into postgres

I tried do this, remembering that my default connection is pgsql

$mysql_model = new Regioni();
$regioni = $mysql_model->setConnection("mysql")->all();

But it's still using pgsql connection.

I'm sure of this because i tried to insert a row into pgsql table, (it was empty), and I can dump this single row as results of all.

Also, I (only for debugging, do not hate me), modified vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php, adding a debug echo into this method

/**
 * Set the connection associated with the model.
 *
 * @param  string|null  $name
 * @return $this
 */
public function setConnection($name)
{
    echo "Model calling setConnection($name)" . PHP_EOL;
    $this->connection = $name;

    return $this;
}

As a result I can see

Model calling setConnection(mysql)
Model calling setConnection()
Model calling setConnection(pgsql)

The first one is the result of my explicit setConnection.

But why calling ->all() will reset connection to default one?

Main goal/question

What's the right way to dinamically change the connection of a model?

1 Answers

I post my actual solution. It's ugly, but it works.

The requisite for this is that default connection is pgsql so I must set connection explicitly to read all table record from nysql

Aftert that, I loop throught and then save to pgsql simply doing an insert at time

    $regioni =  (new Regioni)->setConnection('mysql')->get();
    (new Regioni)->truncate();
    foreach($regioni as $r) {
        (new Regioni)->insert($r->toArray());
    }

Note that this is specifically for my case

  • I have an old mysql to be migrated to the new postgresql
  • I already did migrations on postgresql so all structures are ready
  • I read all data from source and simply write into target postgres
  • this must be done only one time
  • I truncate target before insert (to be repeatable in development)

If you can suggest something more efficient, please, write an answer

Related