Model类增加resultSetType属性 用于指定模型查询的数据集对象(默认为空返回数组) Db类查询不再支持设置自定义数据集对象(只能使用数组或者think\Collection)

This commit is contained in:
thinkphp
2016-12-05 16:24:02 +08:00
parent 30077757bd
commit 405825ff8a
3 changed files with 23 additions and 25 deletions

View File

@@ -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;
}
/**

View File

@@ -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);
}

View File

@@ -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;