1、說明
一般情況下,都是在model中指定一個數(shù)據(jù)庫連接參數(shù)即可。但某些情況下,相同的庫表會在不同地區(qū)都有部署,這個時候需要按地區(qū)進行切換(只有一個model情況下)。
2、多model繼承方式
Model層代碼
//A地區(qū)的數(shù)據(jù)庫
class A extends Model
{
protected $connection = 'xxx';
protected $table = 'xxx';
//其他操作方法
}
//B地區(qū)的數(shù)據(jù)庫
class B extend A
{
protected $connection = 'xxx';
protected $table = 'xxx';
}
使用A地區(qū)的數(shù)據(jù)庫:$model = new A();
使用B地區(qū)的數(shù)據(jù)庫:$model = new B();
3、單model重寫構(gòu)造方法
需要更改地方:config.php配置、重寫Model的構(gòu)造方法文章來源:http://www.zghlxwxcb.cn/news/detail-651021.html
- config.php
點擊查看代碼
return [
"hk" => [
"xxx" => [xxx],//具體的數(shù)據(jù)庫連接參數(shù)
],
"sg" => [
"xxx" => [xxx],//具體的數(shù)據(jù)庫連接參數(shù)
],
];
- 新建一個BaseModel重寫Model的構(gòu)造方法
點擊查看代碼
//自定義Model基類
class BaseModel extends Model
{
/**
* 多地區(qū)數(shù)據(jù)庫配置
* 其中的值必須在config中配置的數(shù)據(jù)庫配置:Config::get('hk.xxx')
* 例如:[
* 'hk' => 'hk.xxx',
* 'sg' => 'sg.xxx'
* ]
* @var array
*/
protected $multi_connections = [];
protected $multi_connections_key;
//重寫構(gòu)造方法
public function __construct($data = [])
{
//通過new model('xx.xx')設(shè)置 connection => 多地區(qū)數(shù)據(jù)庫
if (is_string($data)) {
$this->multi_connections_key = $data;//記錄當前的地區(qū)key
if ($conn = $this->multi_connections[$data]) {
//此時:data=hk
$this->connection = $conn;
} else {
//此時:data=hk.xx,且必須設(shè)置配置文件
$this->connection = $data;
}
$data = [];
}
parent::__construct($data);
}
}
- 在model中使用
點擊查看代碼
class A extends BaseModel
{
//多地區(qū)數(shù)據(jù)庫配置(下面支持sg和kr地區(qū)的切換)
protected $multi_connections = [
'sg' => 'sg.xxx',
'kr' => 'kr.xxx',
];
}
- 在控制器中進行使用
url設(shè)置:http://xxx?region=xxx文章來源地址http://www.zghlxwxcb.cn/news/detail-651021.html
點擊查看代碼
class Demo extends Controller
{
public $region;
protected $mod;
public function _initialize()
{
//獲取當前需要的地區(qū),默認hk
$this->region = input('region', 'hk');
//根據(jù)地區(qū)進行new Model
$this->mod = new A($this->region);
}
//測試方法
public function index()
{
//這里可以使用model的方法
$data = $this->model->xxx()
}
}
到了這里,關(guān)于thinkphp5框架的model支持多地區(qū)數(shù)據(jù)庫切換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!