Query类增加failException方法 用于设置查询没有找到数据时候是否抛出异常

This commit is contained in:
thinkphp
2016-04-23 18:16:26 +08:00
parent c772c23cd8
commit 0ed23d6186
2 changed files with 35 additions and 2 deletions

View File

@@ -89,7 +89,7 @@ abstract class Builder
$result = [];
foreach ($data as $key => $val) {
if (!in_array($key, $fields, true)) {
if ($this->connection->getConfig('fields_strict')) {
if ($options['strict']) {
throw new Exception(' fields not exists :[' . $key . ']');
}
} else {
@@ -572,7 +572,7 @@ abstract class Builder
foreach ($dataSet as &$data) {
foreach ($data as $key => $val) {
if (!in_array($key, $fields, true)) {
if ($this->connection->getConfig('fields_strict')) {
if ($options['strict']) {
throw new Exception(' fields not exists :[' . $key . ']');
}
unset($data[$key]);

View File

@@ -15,6 +15,7 @@ use PDO;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Loader;
use think\Model;
use think\model\Relation;
@@ -795,6 +796,30 @@ class Query
return $this;
}
/**
* 设置是否严格检查字段名
* @access public
* @param bool $strict 是否严格检查字段
* @return $this
*/
public function strict($strict = true)
{
$this->options['strict'] = $strict;
return $this;
}
/**
* 设置查询数据不存在是否抛出异常
* @access public
* @param bool $fail 是否严格检查字段
* @return $this
*/
public function failException($fail = true)
{
$this->options['fail'] = $fail;
return $this;
}
/**
* 指定当前模型
* @access public
@@ -1138,6 +1163,8 @@ class Query
$resultSet = $result->eagerlyResultSet($resultSet, $options['with']);
}
}
} elseif (!empty($options['fail'])) {
throw new DbException('Data not Found', $options, $sql);
}
return $resultSet;
}
@@ -1209,6 +1236,8 @@ class Query
$data->eagerlyResult($data, $options['with']);
}
}
} elseif (!empty($options['fail'])) {
throw new DbException('Data not Found', $options, $sql);
} else {
$data = false;
}
@@ -1320,6 +1349,10 @@ class Query
$options['field'] = '*';
}
if (!isset($options['strict'])) {
$options['strict'] = $this->connection->getConfig('fields_strict');
}
foreach (['master', 'lock', 'fetch_pdo', 'fetch_sql', 'distinct'] as $name) {
if (!isset($options[$name])) {
$options[$name] = false;