Forcing Eloquent models to re resolve database connection

后端 未结 2 1290
你的背包
你的背包 2020-12-21 21:20

Is there any way to force Eloquent models to re resolve the connection they were instantiated with?

Right now I have a method that changes the database connection in

相关标签:
2条回答
  • 2020-12-21 21:44

    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.

    0 讨论(0)
  • 2020-12-21 21:50

    In my case, I did not have a database config for each of my databases, since they are created dynamically. I used the following approach, just changing the table name to include the database name as well (This works for MySQL):

    foreach ($array as $key => $value) {
       $productRepo = new ProductRepository();  
       $productRepo->setTable($key . '_' . $database);  
       $products = $productRepo->all();
    }
    
    0 讨论(0)
提交回复
热议问题