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 env
and model,
I just want to create a new connection when copying records,and then disconnect it when completion.
How to do it?