Laravel 4.2: copying database records from one database to another

I need to copy a subset of records from one database to another in Laravel 4.2

I wrote a craftsman task that loads models that I need to copy from the default connection, and now they need to be saved to a second database connection (which is defined in config / database.php). I cannot find a way to use the save () method to save to a database other than the default connection.

Is it possible? Can I push my data onto a second database connection? Or do I need to go to the “pull” logic, cancel the database connection definitions and load data from the “second” connection before saving to “default”?

+5
source share
2 answers

As @Filip pointed out, before saving the model, you must establish a connection with the model in the second (target) database.

However, it is also necessary to set the id parameter to null (if you are not sure that there is no record with this identifier in the second database, which I could not) to ensure that the new value of the increasing id is highlighted.

And it is also necessary to set the exists property of the model to false before saving. This value is true in the model after reading the record from the source database, because the record was successfully read from there (and was not created as a new record). In case of failure, reset exists Laravel tried UPDATE WHERE id = $model->id , which would not write anything to the database, because there was no suitable record (with a zero identifier) ​​for updating. Setting exists to false ensures that persistence will be performed as an INSERT .

+1
source

First of all, you should define a secret connection in app/conifg/database.php and then in connections , for example:

 'second_db_conn' => [ 'driver' => 'mysql', 'host' => $_SERVER['MYSQL_HOST'], 'database' => $_SERVER['MYSQL_DATABASE'], 'username' => $_SERVER['MYSQL_USERNAME'], 'password' => $_SERVER['MYSQL_PASSWORD'], 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ], 

Then establish this connection on your model - save it - and return to the default (in my example it is mysql ):

 $model->setConnection('second_db_conn')->save(); $model->setConnection('mysql'); 
+1
source

All Articles