2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3で別々のデータベースのテーブルをjoinする方法

Last updated at Posted at 2020-03-30

app.phpに接続情報を明記

2つの「datebase_aのcommentsテーブル」と「datebase_bのusersテーブル」が存在するとします。(usersテーブルとcommentsテーブルを別のデータベースで管理するのはあくまで例です)
1つのusersに複数のcommentsが紐づきます。

config/app.phpに接続情報を明記しましょう。

app.php
'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'username' => 'user_a', 
        'password' => 'password',
        'database' => 'database_a',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'log' => false,
    ],
    'database_b' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'username' => 'user_b', 
        'password' => 'password',
        'database' => 'database_b',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
        'log' => false,
    ],
],

モデルに定義

defaultConnectionName()を使いましょう。

UsersTable.php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class EstatesTable extends Table
{
    public static function defaultConnectionName(){
        return 'database_b';
    }

    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->setTable('users');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');
    }
}

別々のデータベースのテーブルをjoin

UsersController.php
$users = $this->Users->find()
    ->join([
        'table' => 'datebase_a.comments',
        'alias' => 'C',
        'type' => 'LEFT',
        'conditions' => 'C.user_id = Users.id',
    ])
    ->toArray();

参考:公式サイト

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?