cakephp 3中的多个数据库连接

Multiple database connection in cakephp 3

我正在尝试连接到 cakephp 3 中的多个数据库。我试了很多次,但所有的问题和答案都在cakephp 2中。我在 cakephp 3 文档中找到 Configuring Connections 但我无法理解。

我有两个数据库:

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

使用数据库 tracking_system 完全是 运行。 但我不知道如何连接到多个数据库(在我的例子中,第二个数据库tracking_system2)。

在此先感谢您的帮助。

您可以在默认情况下使用另一个连接的表上声明 defaultConnectionName() 方法。在您的任何 Table 类:

public static function defaultConnectionName()  
{
    return 'another_config_name';
}

我找到了问题的解决方案。而且效果很好。请参考下面的代码,如果我在任何地方有错误,请评论。

--> 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
  • 将此行添加到您的控制器

use Cake\Datasource\ConnectionManager;

我的TodolistsController.php代码是:

<?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');
    }
}

就是这样。

谢谢...

您可以尝试使用 useDbConfig 模型 属性 如果它适合您。

class Example extends AppModel {
    public $useDbConfig = 'default1DbConfigSettings'; //The useDbConfig property is defaulted to the ‘default’ database connection.
}

要为模型切换数据库,

使用 controller/model

中的命名空间
use Cake\Datasource\ConnectionManager;

在控制器中;-

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

模型中:-

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

这是 CakePHP 3 的答案。*