diff --git a/library/think/Model.php b/library/think/Model.php index 8c9679b8..b18ee28c 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -183,7 +183,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * @param bool $master 是否从主库读取 * @return void */ - public function readMaster($master) + public function readMaster($master = true) { if ($master) { static::$readMaster[$this->class] = true; diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index 731cb49a..cca6923e 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -451,24 +451,24 @@ abstract class Connection $this->debug(false); if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) { - $query->setModelReadMaster(true); + $query->readMaster(true); } $this->numRows = $this->PDOStatement->rowCount(); return $this->numRows; } catch (\PDOException $e) { if ($this->isBreak($e)) { - return $this->close()->execute($sql, $bind); + return $this->close()->execute($sql, $bind, $query); } throw new PDOException($e, $this->config, $this->getLastsql()); } catch (\Throwable $e) { if ($this->isBreak($e)) { - return $this->close()->execute($sql, $bind); + return $this->close()->execute($sql, $bind, $query); } throw $e; } catch (\Exception $e) { if ($this->isBreak($e)) { - return $this->close()->execute($sql, $bind); + return $this->close()->execute($sql, $bind, $query); } throw $e; } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index f063b07c..8ca880fd 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -53,6 +53,8 @@ class Query protected static $info = []; // 回调事件 private static $event = []; + // 读取主库 + private static $readMaster = []; /** * 构造函数 @@ -141,16 +143,20 @@ class Query } /** - * 设置模型从主库读取数据 + * 设置后续从主库读取数据 * @access public * @param bool $master * @return void */ - public function setModelReadMaster($master = true) + public function readMaster($master = true) { - if ($this->model) { - $this->model->readMaster($master); + if ($master) { + $table = isset($this->options['table']) ? $this->options['table'] : $this->getTable(); + + static::$readMaster[$table] = true; } + + return $this; } /** @@ -2936,6 +2942,10 @@ class Query } } + if (isset(static::$readMaster[$options['table']])) { + $options['master'] = true; + } + foreach (['join', 'union', 'group', 'having', 'limit', 'order', 'force', 'comment'] as $name) { if (!isset($options[$name])) { $options[$name] = '';