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时,就可建立不同连接进行操作,不会出现上面的问题了。
 

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