I need to copy a subset of records from one database to another in Laravel 4.2
I've written an artisan task that loads the models that I need to copy from the "default" database connection, and now need to save them to the second database connection (which is defined in config/database.php). What I can't find is any way to use the model's save() method to save to a database other than the default connection.
Is this possible? Can I "push" my saves to the second database connection? Or do I need to change to a "pull" logic, reverse my database connection definitions, and load the data from the "second" connection before saving to the "default"?
First of all you have to define the secoundary 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 set this connection on yout model - save it - and switch back to the default (in my example is a mysql
):
$model->setConnection('second_db_conn')->save();
$model->setConnection('mysql');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With