更改cakephp3中的默认数据库

问题描述 投票:0回答:1

在控制器中我想更改默认数据库,以便我可以从网站的任何位置访问新的数据库(db2)。 db2数据库具有相同的模型,但只有不同的数据。我的代码只访问其他数据库,但没有将新的默认数据库设置为db2,可以在网站的任何地方访问。我没有得到以下帖子的答案。

这是我的控制器:

$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured 
$results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc');
//this works but doesnt set the default database to db2 everywhere

这是我的app.php:

'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_test',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],

    'db2' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',

        //'port' => 'non_standard_port_number',
        'username' => 'root',
        'password' => '',
        'database' => 'aptutori_testbak',
        'encoding' => 'utf8',
        'timezone' => '+11:00',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,

        'quoteIdentifiers' => false,

        'url' => env('DATABASE_URL', null),
    ],

Dynamically change database connection in cakephp 3

http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database

cakephp cakephp-3.0
1个回答
2
投票

使用ConnectionManager::alias()

http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias

例如,这将使所有需要default连接的表使用db2

ConnectionManager::alias('db2', 'default');
© www.soinside.com 2019 - 2024. All rights reserved.