diff --git a/library/think/Model.php b/library/think/Model.php index 6a6841a6..68688759 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -111,6 +111,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $useGlobalScope = true; // 是否采用批量验证 protected $batchValidate = false; + // 查询数据集对象 + protected $resultSetType; /** * 初始化过的模型. @@ -574,7 +576,15 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function toCollection($collection) { - return new Collection($collection); + if ($this->resultSetType) { + if ('collection' == $this->resultSetType) { + $collection = new Collection($collection); + } else { + $class = $this->resultSetType; + $collection = new $class($collection); + } + } + return $collection; } /** diff --git a/library/think/db/Connection.php b/library/think/db/Connection.php index d9b7978f..f7d33161 100644 --- a/library/think/db/Connection.php +++ b/library/think/db/Connection.php @@ -489,10 +489,7 @@ abstract class Connection $result = $this->PDOStatement->fetchAll($this->fetchType); $this->numRows = count($result); - if (!empty($class)) { - // 返回指定数据集对象类 - $result = new $class($result); - } elseif ('collection' == $this->resultSetType) { + if ('collection' == $this->resultSetType) { // 返回数据集Collection对象 $result = new Collection($result); } diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 4d63ba14..a2c0f211 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1318,18 +1318,6 @@ class Query return $this; } - /** - * 指定数据集返回对象 - * @access public - * @param string $class 指定返回的数据集对象类名 - * @return $this - */ - public function fetchClass($class) - { - $this->options['fetch_class'] = $class; - return $this; - } - /** * 设置从主服务器读取数据 * @access public @@ -1967,12 +1955,11 @@ class Query } } - // 返回结果处理 - if (count($resultSet) > 0) { - // 数据列表读取后的处理 - if (!empty($this->model)) { - // 生成模型对象 - $model = $this->model; + // 数据列表读取后的处理 + if (!empty($this->model)) { + // 生成模型对象 + $model = $this->model; + if (count($resultSet) > 0) { foreach ($resultSet as $key => $result) { /** @var Model $result */ $result = new $model($result); @@ -1983,12 +1970,16 @@ class Query } $resultSet[$key] = $result; } - if (!empty($options['with']) && $result instanceof Model) { + if (!empty($options['with'])) { // 预载入 $result->eagerlyResultSet($resultSet, $options['with'], is_object($resultSet) ? get_class($resultSet) : ''); } } - } elseif (!empty($options['fail'])) { + // 模型数据集转换 + $resultSet = (new $model)->toCollection($resultSet); + } + // 返回结果处理 + if (!empty($options['fail']) && count($resultSet) == 0) { $this->throwNotFound($options); } return $resultSet;