-1

How to switch databases flexibly in laravel?

For example:
There is a database db,it has a table articles

id
title
content
status   //this field has 3 values: 1 or 2 or 3

There are 3 other databases db1,db2,db3 on the same host,
there is a table articles in each database,they have the same structure:

id
title
content
status

At present,db is using:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
//...

Now query articles via diffrent status form db:

class TestController extends Controller
{
    public function copyArticles()
    {
        $articles_status_1 = Article::where('status', 1)->get();  
        $articles_status_2 = Article::where('status', 2)->get();
        $articles_status_3 = Article::where('status', 3)->get();
    }
}

Then I want to save them to target databases:

copy `$articles_status_1` to `articles` in `db1`
copy `$articles_status_2` to `articles` in `db2`
copy `$articles_status_3` to `articles` in `db3`

So,I need to switch databases,
I don't want to add configs into envand model,
I just want to create a new connection when copying records,and then disconnect it when completion.

How to do it?

zwl1619
  • 4,002
  • 14
  • 54
  • 110
  • 1
    Possible duplicate of [How to use multiple database in Laravel](https://stackoverflow.com/questions/31847054/how-to-use-multiple-database-in-laravel) – Thamilhan Aug 31 '17 at 11:37

1 Answers1

0

in your database config you can add 3 other connection for db1,db2 and db3 like that

'mysql1' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'db1'),
    ....................
],

'mysql2' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => 'db2',
   ..............
],

after in your controler you call

DB::setDefaultConnection('mysql1');

after you save your article in the db1

after you switch et the db 2

DB::setDefaultConnection('mysq12');

you save your article in the db2 ..................