LoginSignup
22
21

More than 5 years have passed since last update.

【CakePHP3】複数データベース接続を実現する方法

Posted at

default以外へのデータベース接続を試みましたが、単純にapp.phpに接続設定を追加して、TableにuseDbConfigを足しただけではうまくできませんでした。いろいろ調べて接続できるようになったので、対応方法をメモしておきます。

環境

  • CentOS7
  • CakePHP 3.2.12
  • PHP 7.0.9
  • Apache 2.4.6

対応方法

行うことは以下の2点です。

1 app.phpに設定を追加

app.php

//default以外に新たにDB接続設定を追加します
'another_db' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'another_host',
            'username' => 'another_username',
            'password' => 'another_password',
            'database' => 'another_database',
            'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            'log' => false,
            'url' => env('DATABASE_TEST_URL', null),
        ],

2 Tableファイルに関数を作成

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

class SamplesTable extends Table
{
    ...
    //この関数を追加します
    public static function defaultConnectionName(){
        return 'another_db';
    }

    ...
}

これでSamplesTableanother_dbに接続できました! :smiley:

参考文献

22
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
21