CakePHP using multiple databases for models

前端 未结 3 1214
野性不改
野性不改 2021-01-06 06:19

Is it possible for certain models to be in one database and other models in another (using the same connection)?

I have a number of read-only tables that I want shar

相关标签:
3条回答
  • 2021-01-06 06:51

    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.*

    0 讨论(0)
  • 2021-01-06 06:57

    I've built a site in CakePHP that has models using different databases and I never had problem with joins across different databases - the framework seemed to take care of all that for me. Though you might need to explicitly state the database tables used in your models to get it to work.

    0 讨论(0)
  • 2021-01-06 07:14

    This site has a way to do it, but it's a little hacky.

    0 讨论(0)
提交回复
热议问题