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' => ['用戶信息未找到'])));
}
}
}
(完)