ThinkPHP 5複数のデータベースクエリの注意事項

6226 ワード

  • データベース切替i.config.phpにデータベース構成配列
  • を追加
    //     1
    'db_config1' => [
    //      
    'type' => 'mysql',
    //      
    'hostname' => '127.0.0.1',
    //     
    'database' => 'thinkphp',
    //       
    'username' => 'root',
    //      
    'password' => '',
    //          utf8
    'charset' => 'utf8',
    //       
    'prefix' => 'think_',
    ],
    //     2
    'db_config2' => 'mysql://root:1234@localhost:3306/thinkphp#utf8';

    クエリー文を(ここではtable()メソッドを'->'で接続します)に変更します.前は':')
    Db::connect('db_config1')->table('test1')->field('*')->select();
    Db::connect('db_config2')->table('test1')->field('*')->select();
  • 特定のSQL文をTP 5に変更したチェーン操作元のSQL文は以下の通りである:
  • SELECT parent.name, COUNT(product.name)
    FROM nested_category AS node,
    nested_category AS parent,
    product
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.category_id = product.category_id
    GROUP BY parent.name
    ORDER BY node.lft

    デフォルトのデータベース構成を使用する場合
    $res = Db::table('nested_category node,nested_category parent,product')
                ->field('parent.name,count(product.name)')
                ->where('node.category_id','exp', '= product.category_id')
                ->where('node.lft','exp', 'between parent.lft and parent.rgt')
                ->group('parent.name')
                ->order('node.lft')
                ->select();

    2番目のデータベース構成を使用する場合(table()の前に'->'で接続します.複数のデータベース名を'[]で囲み、配列に変換)
    $testConnect = Db::connect('test_conf');
    $res = $testConnect->table(['nested_category node,nested_category parent,product'])
                ->field('parent.name,count(product.name)')
                ->where('node.category_id','exp', '= product.category_id')
                ->where('node.lft','exp', 'between parent.lft and parent.rgt')
                ->group('parent.name')
                ->order('node.lft')
                ->select();