1、数据库配置中账号密码要使用root账号密码
2、管理员数据添加和小改的时候,关联城市
3、创建和修改管理员的时候
- 判断是否有数据库
- 创建数据库
- 导入sql
- 修改数据库配置信息
//获取管理员数据、根据自己需求修改
$getadminInfo=$this->auth->getInfo();
//拼接省市区id,可以根据自己需求修改
$city= implode('_', $getadminInfo["city"]);
// 数据库拼接城市id
$Cachecity="cache_city_mysql_".$city;
//判断是否有数据库名称缓存
if(Cache::get($Cachecity)){
// Cache::set($Cachecity,$Cachecity);
//数据库是否能链接
$cityDATABASE=Db::connect($Cachecity) ->table('ba_cms_search_log') ->find();
if(empty($cityDATABASE)){
//不能链接的话创建数据库
/******创建数据库*****/
//创建数据库
Db::execute("CREATE DATABASE ".$Cachecity.";");
/***********导入sql*************/
// sql文件目录
$filePath = app()->getRootPath() . 'public/mysql/';
// 连接数据库
$connection = Db::connect($Cachecity);
// 打开目录
$handle = opendir($filePath);
// 遍历目录中的文件和子目录
while ($file = readdir($handle)) {
if ($file!= '.' && $file!= '..') {
// 获取文件中的内容
$sql = file_get_contents($filePath.$file) ;
//执行sql语法
$connection->execute($sql) ;
}
}
// 关闭目录句柄
closedir($handle);
/********导入sql结束********/
/************修改数据库配置***********/
// 获取当前的数据库配置信息
$config = config('database');
// // 添加或修改数据库配置信息
$config['connections'][$Cachecity] =$config['connections']["mysql"] ;
$config['connections'][$Cachecity]["hostname"] = '127.0.0.1'; // 替换为新的主机名
$config['connections'][$Cachecity]['username'] = 'root'; // 替换为新的用户名
$config['connections'][$Cachecity]['password'] = 'c8181aeb7f56966f'; // 替换为新的密码
$config['connections'][$Cachecity]['database'] = $Cachecity; // 替换为新的数据库名
// // 更新数据库配置
config('database', $config);
// 写入配置信息到配置文件
$configFile = app()->getRootPath() . 'config/database.php'; // 替换为你的配置文件名
$content = "<?php return ".var_export($config, true).";";
file_put_contents($configFile, $content);
/*********修改数据库配置结束************/
/************创建数据库结束***************/
}else{
}
//判断数据库是否存在
}
4、在需要切换数据库的控制器中加入
public function initialize(): void
{
parent::initialize();
$this->tree = Tree::instance();
$this->model = new \app\admin\model\cms\Channel;
/**************对应数据库******************/
//获取管理员数据、根据自己需求修改
$getadminInfo=$this->auth->getInfo();
if(!empty($getadminInfo["city"])){
//拼接省市区id,可以根据自己需求修改
$city= implode('_', $getadminInfo["city"]);
// 数据库拼接城市id
$Cachecity="cache_city_mysql_".$city;
//切换数据库
$this->model ->setConnection($Cachecity);
}
/**************对应数据库结束******************/
}
同样的,前段只要有对应得城市拼接数据库的字符串,就能在对应接口进行切换数据库了