如果我們想為某個(gè)應(yīng)用單獨(dú)配置數(shù)據(jù)庫,可以如下操作(舉例為微信平臺(tái)(wechat)應(yīng)用單獨(dú)配置數(shù)據(jù)庫):
<?php
$system_config = config('thinkorm');
$default = $system_config['connections'][$system_config['default']];
$hostname = '鏈接地址';
$hostport = '端口';
$database = '數(shù)據(jù)庫名稱';
$username = '數(shù)據(jù)庫賬戶';
$password = '數(shù)據(jù)庫密碼';
$charset = '編碼';
$prefix = '表前綴';
$system_config['connections']['wechat'] = [
// 數(shù)據(jù)庫類型
'type' => 'mysql',
// 服務(wù)器地址
'hostname' => $hostname,
// 數(shù)據(jù)庫名
'database' => $database,
// 數(shù)據(jù)庫用戶名
'username' => $username,
// 數(shù)據(jù)庫密碼
'password' => $password,
// 數(shù)據(jù)庫連接端口
'hostport' => $hostport,
// 數(shù)據(jù)庫連接參數(shù)
'params' => [],
// 數(shù)據(jù)庫編碼默認(rèn)采用utf8
'charset' => $charset,
// 數(shù)據(jù)庫表前綴
'prefix' => $prefix,
// 斷線重連
'break_reconnect' => true,
// 關(guān)閉SQL監(jiān)聽日志
'trigger_sql' => false,
// 開啟自動(dòng)寫入時(shí)間戳字段
'auto_timestamp' => true,
];
return $system_config;
<?php
return [
plugin\wechat\app\bootstrap\ThinkOrm::class
];
<?php
namespace plugin\wechat\app\bootstrap;
use Throwable;
use Webman\Bootstrap;
use Workerman\Timer;
use think\Paginator;
use think\facade\Db;
use think\db\connector\Mysql;
class ThinkOrm implements Bootstrap
{
// 進(jìn)程啟動(dòng)時(shí)調(diào)用
public static function start($worker)
{
$config = config('plugin.wechat.thinkorm');
$default = $config['default'] ?? false;
$connections = $config['connections'] ?? [];
// 配置
Db::setConfig($config);
// 維持mysql心跳
if ($worker) {
Timer::add(55, function () use ($connections, $default) {
if (!class_exists(Mysql::class, false)) {
return;
}
foreach ($connections as $key => $item) {
if ($item['type'] == 'mysql') {
try {
if ($key == $default) {
Db::query('select 1');
} else {
Db::connect($key)->query('select 1');
}
} catch (Throwable $e) {}
}
}
Db::getDbLog(true);
});
}
Paginator::currentPageResolver(function ($pageName = 'page') {
$page = request()->input($pageName, 1);
if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int)$page >= 1) {
return (int)$page;
}
return 1;
});
}
}
// 設(shè)置當(dāng)前模型的數(shù)據(jù)庫連接
protected $connection = 'wechat';