如果我们想为某个应用单独配置数据库,可以如下操作(举例为微信平台(wechat)应用单独配置数据库):
<?php
$system_config = config('thinkorm');
$default = $system_config['connections'][$system_config['default']];
$hostname = '链接地址';
$hostport = '端口';
$database = '数据库名称';
$username = '数据库账户';
$password = '数据库密码';
$charset = '编码';
$prefix = '表前缀';
$system_config['connections']['wechat'] = [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => $hostname,
// 数据库名
'database' => $database,
// 数据库用户名
'username' => $username,
// 数据库密码
'password' => $password,
// 数据库连接端口
'hostport' => $hostport,
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => $charset,
// 数据库表前缀
'prefix' => $prefix,
// 断线重连
'break_reconnect' => true,
// 关闭SQL监听日志
'trigger_sql' => false,
// 开启自动写入时间戳字段
'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
{
// 进程启动时调用
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;
});
}
}
// 设置当前模型的数据库连接
protected $connection = 'wechat';