天天看點

TP5配置database.php使用多個資料庫

TP5配置使用多個資料庫方法

1、修改database.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------

return [

    'db1' => [
        // 資料庫類型
        'type' => 'mysql',
        // 伺服器位址
        'hostname' => '192.168.1.1',
        // 資料庫名
        'database' => 'db1',
        // 使用者名
        'username' => 'root',
        // 密碼
        'password' => 'password',
        // 端口
        'hostport' => '3306',
        // 連接配接dsn
        'dsn' => '',
        // 資料庫連接配接參數
        'params' => [],
        // 資料庫編碼預設采用utf8
        'charset' => 'utf8',
        // 資料庫表字首
        'prefix' => 'think_',
        // 資料庫調試模式
        'debug' => true,
        // 資料庫部署方式:0 集中式(單一伺服器),1 分布式(主從伺服器)
        'deploy' => 0,
        // 資料庫讀寫是否分離 主從式有效
        'rw_separate' => false,
        // 讀寫分離後 主伺服器數量
        'master_num' => 1,
        // 指定從伺服器序号
        'slave_no' => '',
        // 是否嚴格檢查字段是否存在
        'fields_strict' => true,
        // 資料集傳回類型
        'resultset_type' => 'array',
        // 自動寫入時間戳字段
        'auto_timestamp' => false,
        // 時間字段取出後的預設時間格式
        'datetime_format' => 'Y-m-d H:i:s',
        // 是否需要進行SQL性能分析
        'sql_explain' => false
    ],
    'db2' => [
        // 資料庫類型
        'type' => 'mysql',
        // 伺服器位址
        'hostname' => '222.7.2.2',
        // 資料庫名
        'database' => 'db2',
        // 使用者名
        'username' => 'root',
        // 密碼
        'password' => 'password',
        // 端口
        'hostport' => '3306',
        // 連接配接dsn
        'dsn' => '',
        // 資料庫連接配接參數
        'params' => [],
        // 資料庫編碼預設采用utf8
        'charset' => 'utf8',
        // 資料庫表字首
        'prefix' => 'big_',
        // 資料庫調試模式
        'debug' => true,
        // 資料庫部署方式:0 集中式(單一伺服器),1 分布式(主從伺服器)
        'deploy' => 0,
        // 資料庫讀寫是否分離 主從式有效
        'rw_separate' => false,
        // 讀寫分離後 主伺服器數量
        'master_num' => 1,
        // 指定從伺服器序号
        'slave_no' => '',
        // 是否嚴格檢查字段是否存在
        'fields_strict' => true,
        // 資料集傳回類型
        'resultset_type' => 'array',
        // 自動寫入時間戳字段
        'auto_timestamp' => false,
        // 時間字段取出後的預設時間格式
        'datetime_format' => 'Y-m-d H:i:s',
        // 是否需要進行SQL性能分析
        'sql_explain' => false,
    ],

];
           

2、修改db.php 路徑: thinkphp/think/libary/db.php 

修改connect方法

添加代碼:

public static $config_db=[];      
if(!empty($config))
{
    self::$config_db = $config;
}
if(empty($config) && !empty(self::$config_db))
{
    $config = self::$config_db;
}
           
/**
     * @var int 執行次數
     */
    public static $executeTimes = 0;
    public static $config_db=[];

    /**
     * 資料庫初始化,并取得資料庫類執行個體
     * @access public
     * @param  mixed       $config 連接配接配置
     * @param  bool|string $name   連接配接辨別 true 強制重新連接配接
     * @return Connection
     * @throws Exception
     */
    public static function connect($config = [], $name = false)
    {
        if(!empty($config))
        {
            self::$config_db = $config;
        }
        if(empty($config) && !empty(self::$config_db))
        {
            $config = self::$config_db;
        }

        if (false === $name) {
            $name = md5(serialize($config));
        }

        if (true === $name || !isset(self::$instance[$name])) {
            // 解析連接配接參數 支援數組和字元串
            $options = self::parseConfig($config);

            if (empty($options['type'])) {
                throw new \InvalidArgumentException('Undefined db type');
            }

            $class = false !== strpos($options['type'], '\\') ?
            $options['type'] :
            '\\think\\db\\connector\\' . ucwords($options['type']);

            // 記錄初始化資訊
            if (App::$debug) {
                Log::record('[ DB ] INIT ' . $options['type'], 'info');
            }

            if (true === $name) {
                $name = md5(serialize($config));
            }

            self::$instance[$name] = new $class($options);
        }

        return self::$instance[$name];
    }
           

3、使用構造函數,正常使用,文法不變

class Detect extends Controller
{
    public function __construct()
    {
        Db::$config_db=config("database.db1");

    }
    /**
     *
     * 6、送出測評接口
     * 本接口用于送出測評
     */
    public function add()
    {
        $userId = session('userId');       //擷取session
        if ($userId == "") {
            return array("status" => '1', 'error' => ['請登入']);
        }
        $id = input('post.fileId'); //檔案ID
        $result = Db::field('id,file_name,app_name,version,size,path')
            ->table(['app_file' => 'file'])
            ->where('file.id', $id)
            ->find();
        print_r($result);
}
           

4、其他應用子產品(application2)使用

class User extends Controller
{
    public function __construct()
    {
        $db = include $file = "../honor/database.php";
        Db::$config_db = $db['db1'];

    }

    /**
     * 1、使用者基本資訊
     */
    public function userDetail()
    {

        $userId = session('userId');       //擷取session 

        if ($userId == "") {
            exit(json_encode(array("status" => '1', 'error' => ['使用者資訊未找到'])));
        }

        $result = Db::field('user.user_name userName,user.head,user.mobile,user.email')
            ->table(['t_user' => 'user'])
            ->where('user.id', $userId)
            ->where('user.status', '0')
            ->find();
        if ($result) {
            exit(json_encode(array("status" => '0', 'data' => $result)));
        } else {
            exit(json_encode(array("status" => '1', 'error' => ['使用者資訊未找到'])));
        }

    }
}
           

(完)