CakePHP switch database (using same datasource) on the fly?

前端 未结 2 1436
说谎
说谎 2020-12-03 06:08

I have tried to build a small function that would be use in controller to switch database on the fly, i must use only one datasource.

On my database.php :

         


        
2条回答
  •  忘掉有多难
    2020-12-03 06:51

    I just wanted to tell that nowadays it's really simple to change current model's datasource (database connection):

    For example in my PersonsController index:

    public function index() {
    
        //change to a different datasource which is already written in App/Config/database.php-file
        $this->Person->setDataSource('testdb2');
        $persons = $this->Person->find('all');
        $this->set('db1persons', $persons);
    
        //change to a different database
        $this->Person->setDataSource('testdb');
        $persons = $this->Person->find('all');
        $this->set('db2persons', $persons);
    }
    

    As you can see the key here is to use $this->Model->setDataSource()

提交回复
热议问题