0
0

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 3 years have passed since last update.

MySQLで複数のDBをまたいで使用する

Posted at

概要

サービスが大きくなったりしてDBが増えたときに、複数のDBをまたいで使用する場合の書き方です。

環境

PHP 5.3.29
FuelPHP 1.7.3
MySQL 5.5.61

本題

方法1

まず、FuelPHPのfuel/app/config以下にあるdb.phpに設定を書きます。書くファイルはそれぞれの環境に応じたものにします。(開発環境であればdevelopment/db.php
ここに複数の設定を書けばクエリを発行する際に各DBを指定して使用できます。

db.php
<?php
return array{
  'db01' => array(
    'type'        => 'pdo',
    'connection'  => array(
      'dsn'        => 'mysql:host=localhost;dbname=db01',
      'username'   => '',
      'password'   => '',
    ),
  ),
  'db02' => array(
    'type'        => 'pdo',
    'connection'  => array(
      'dsn'        => 'mysql:host=localhost;dbname=db02',
      'username'   => '',
      'password'   => '',
    ),
  ),
  'db03' => array(
    'type'        => 'pdo',
    'connection'  => array(
      'dsn'        => 'mysql:host=localhost;dbname=db03',
      'username'   => '',
      'password'   => '',
    ),
  ),
);
?>

各パラメータは各々の環境に合わせます。

次に、モデルにクエリを発行する文を書きます。

examplemodel.php
<?php
namespace Example;
class Model_Examplemodel extends \Model
{
  public static function get_example()
  {
    $get = \DB::select()
    ->from('tablename')
    ->execute('db01')
    return $get;
  }
}
?>

このようにexecute()の引数にdb.phpで定義した文字を入れればそのDBを参照してくれます。

方法2

セレクトするテーブルの情報にDB名を加える形でも可能です。

examplemodel.php
<?php
namespace Example;
class Model_Examplemodel extends \Model
{
  public static function get_example()
  {
    $get = \DB::select()
    ->from('db01.tablename')
    ->execute()
    return $get;
  }
}
?>

joinする場合

joinする場合は、方法1をとるとすべてそのDBにあるテーブルが参照されます。
ですので、db01・db02それぞれからテーブルを参照する必要がある場合は方法2、もしくは両方を合わせて使う必要があります。

examplemodel.php
<?php
namespace Example;
class Model_Examplemodel extends \Model
{
  public static function get_example()
  {
    $get = \DB::select()
    ->from('db01.table01')
    ->join('db02.table02')
    ->on('table01.column01', '=', 'table02.column01')
    ->execute()
    return $get;
  }
}
?>

カラム名が被っている場合はその点にも注意します。

終わりに

FuelPHPを書いていて、発行されたクエリが簡単にわかる方法はないかなーと思って探しています。知っている方いましたらコメントいただけるとすごく助かります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?