thinkphp5數據庫分庫時model操作支持

使用thinkphp5.0實現業務功能時,遇到一個問題,同表分庫場景下,用model類實例無法支持多數據庫sql操作。

場景如下:
db1.test
db2.test
db3.test
...

當使用:

$model = new Test([],'db1');
$model->where('id',1)->find();

$model = new Test([],'db2');
$model->where('id',2)->find();
當我們要查詢db2的數據表時,查到的還是db1.test表的。

解決辦法:

thinkphp/library/think/Model.php  259行

public function getQuery($buildNewQuery = false)
    {
        if ($buildNewQuery) {
            return $this->buildQuery();
        } elseif (!isset(self::$links[$this->class])) {
            // 創建模型查詢對象
            self::$links[$this->class] = $this->buildQuery();
        }
        return self::$links[$this->class];
    }

改造爲:

public function getQuery($buildNewQuery = false)
    {
        if ($buildNewQuery) {
            return $this->buildQuery();
        } elseif (!isset(self::$links[$this->class.':'.($this->connection['database']??'')])) {
            // 創建模型查詢對象
            self::$links[$this->class.':'.($this->connection['database']??'')] = $this->buildQuery();
        }
        return self::$links[$this->class.':'.($this->connection['database']??'')];
    }

這樣同一model在不同database時,就可建立不同連接進行操作,不會出現上面的問題了。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章