13

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. I found Configuring Connections at cakephp 3 documentation. But I can't understand it.

I have two databases :

1. tracking_system
     (Tables: trackers, events, etc..)
2. tracking_system_2
     (Tables: todos, actions, etc..)

Working with database tracking_system is completely running. But I don't know, how to connect to multiple databases (in my case, with second database tracking_system2).

Thanks in advance for help.

4
  • The docs are pretty clear about how to make tables use specific connections, so you should be a little more specific as to what exactly your problem is, what exactly you don't understand, "I don't understand" is not helpful, and "I don't know how to connect..." could mean anything.
    – ndm
    Commented May 1, 2015 at 12:26
  • @ndm can you please add a link to the doc where Jigar can take a look at.
    – shadab
    Commented May 2, 2015 at 16:30
  • @Sam Have a closer look at the question, he linked to it himself.
    – ndm
    Commented May 2, 2015 at 16:36
  • I don't know whether Jigar's problem was solved or not. But, with the link he shared within his question, saved me lots of efforts and time. Thanks @JigarDhaduk Commented Dec 13, 2017 at 18:32

4 Answers 4

10

You can declare the defaultConnectionName() method on the tables that will use by default another connection. In any of your Table classes:

public static function defaultConnectionName()  
{
    return 'another_config_name';
}
2
  • 5
    defaultConnection() didn't work for me. defaultConnectionName() did. Commented Mar 24, 2016 at 19:13
  • The documentation clearly states defaultConnection**Name**() as the function name. Other thing it must be a static function. Commented Jun 24, 2017 at 20:21
10

I get a solution of my problem. And it's working good. Please refer the below code and comment if I am wrong at any place.

--> app.php

'Datasources' => [
'default' => [
    'className' => 'Cake\Database\Connection',
    'driver' => 'Cake\Database\Driver\Mysql',
    'persistent' => false,
    'host' => 'localhost',
    //'port' => 'nonstandard_port_number',
    'username' => 'your_username',
    'password' => 'your_password',
    'database' => 'tracking_system', // This is my default database
    'encoding' => 'utf8',
    'timezone' => 'UTC',
    'cacheMetadata' => true,
    'quoteIdentifiers' => false,
    //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
],

'db2' => [
    'className' => 'Cake\Database\Connection',
    'driver' => 'Cake\Database\Driver\Mysql',
    'persistent' => false,
    'host' => 'localhost',
    //'port' => 'nonstandard_port_number',
    'username' => 'your_username',
    'password' => 'your_password',
    'database' => 'tracking_system2', // This is my second database
    'encoding' => 'utf8',
    'timezone' => 'UTC',
    'cacheMetadata' => true,
    'quoteIdentifiers' => false,
    //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
 ]
]

--> TodolistsController.php

database name: tracking_system2

table name: todolists
  • add this line to your controller

use Cake\Datasource\ConnectionManager;

my TodolistsController.php code is:

<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\ORM\Entity;
use Cake\Network\Exception\NotFoundException;
use Cake\Datasource\ConnectionManager; // This line is required

class TodolistsController extends AppController
{
public function todoadd(){
    $connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured 
    $results = $connection->execute('SELECT * FROM todolists')->fetchAll('assoc');
    $this->set('results', $results);
    if($this->request->is('post')){
        $connection->insert('todolists', [
            'title' => $this->request->data['title'],
            'description' => $this->request->data['description']
        ]);
        $this->redirect($this->referer);
    }
}
}

--> TodolistsTable.php

<?php
namespace App\Model\Table;
use Cake\ORM\Table;

class TodolistsTable extends Table
{
    public static function defaultConnectionName()
    {
        return 'db2';
    }
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
    }
}

That's it.

Thank You...

1
  • Putting SQL code in your controller is against the model logic. You should never write your own SQL code in CakePHP unless in very special cases. Model methods provide all functionality you would mostly need. Commented Apr 25, 2016 at 16:52
0

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

-1

You can have a try with useDbConfig model property if it works for you.

class Example extends AppModel {
    public $useDbConfig = 'default1DbConfigSettings'; //The useDbConfig property is defaulted to the ‘default’ database connection.
}
1
  • 1
    This is not Cake2 question.
    – makallio85
    Commented Jan 26, 2016 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.