Each database is really a separate connection, so I would setup all the connections to the database in the config/database.php
file, and then you can use the setConnection()
method on the model to switch between them.
database.php:
return [
'default' => 'mysql-key1',
'connections' => [
'mysql-key1' => [
'driver' => 'mysql',
'database' => 'key1_dbname,
// etc
],
'mysql-key2' => [
'driver' => 'mysql',
'database' => 'key2_dbname',
// etc
]
]
];
ProductRepository.php:
public function setConnection($name) {
// assumes $this->product is your Product model
$this->product->setConnection($name);
}
Code:
$productRepo = new ProductRepository();
foreach ($array as $key => $value) {
$productRepo->setConnection($key . '_' . $database);
$products = $productRepo->all();
}
Edit
additional information based on comments
Laravel is only going to instantiate a connection to the database the first time it is needed. Once the connection has been created, it is going to reuse it. It would be a huge performance issue if you had to reconnect to the database for every single query.
That being said, if you really want to do this the way you originally designed it, all you would need to do is call the DB::reconnect()
method after updating the config.
foreach ($array as $key => $value) {
Config::set('database.connections.mysql.database', $key . '_' . $database);
DB::reconnect();
$productRepo = new ProductRepository();
$products = $productRepo->all();
}
However, I would strongly urge you to consider the originally described option so that you're not making a ton of unnecessary connections.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…