Multiple database connection in cakephp 3

前端 未结 4 859
长情又很酷
长情又很酷 2020-12-09 04:55

I am trying to connect to multiple databases in cakephp 3. I have tried many times but all questions and answers are in cakephp 2

4条回答
  •  感动是毒
    2020-12-09 05:21

    To switch the database for the model,

    Use the namespace in the controller/model

    use Cake\Datasource\ConnectionManager;
    

    In controller;-

    $conn = ConnectionManager::get('remote_db_1');
    $this->ModelName->connection($conn);
    

    In model:-

    $conn = ConnectionManager::get('remote_db_1');
    $this->connection($conn);
    

    Note:- If you are saving data for the associated tables too, then keep in mind to change the DB for the associated data otherwise data for the associated table will be inserted into the default connection/DB.

    This is the answer for CakePHP 3.*

提交回复
热议问题