find()返回一个一维数组,select()返回一个二维数组,所以在取值时有所不同,一维数组取值用$data["n"],二维数组取值用$data[0]["n"]
* * * * *
find()
think\Db
class Query
~~~
/**
* 查找单条记录
* @access public
* @param array|string|Query|\Closure $data
* @return array|false|\PDOStatement|string|Model
* @throws DbException
* @throws ModelNotFoundException
* @throws DataNotFoundException
*/
public function find($data = null)
{
if ($data instanceof Query) {
return $data->find();
} elseif ($data instanceof \Closure) {
call_user_func_array($data, [ & $this]);
$data = null;
}
// 分析查询表达式
$options = $this->parseExpress();
$pk = $this->getPk($options);
if (!is_null($data)) {
// AR模式分析主键条件
$this->parsePkWhere($data, $options);
} elseif (!empty($options['cache']) && true === $options['cache']['key'] && is_string($pk) && isset($options['where']['AND'][$pk])) {
$key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
}
$options['limit'] = 1;
$result = false;
if (empty($options['fetch_sql']) && !empty($options['cache'])) {
// 判断查询缓存
$cache = $options['cache'];
if (true === $cache['key'] && !is_null($data) && !is_array($data)) {
$key = 'think:' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
} elseif (is_string($cache['key'])) {
$key = $cache['key'];
} elseif (!isset($key)) {
$key = md5(serialize($options) . serialize($this->bind));
}
$result = Cache::get($key);
}
if (false === $result) {
// 生成查询SQL
$sql = $this->builder->select($options);
// 获取参数绑定
$bind = $this->getBind();
if ($options['fetch_sql']) {
// 获取实际执行的SQL语句
return $this->connection->getRealSql($sql, $bind);
}
if (is_string($pk)) {
if (!is_array($data)) {
if (isset($key) && strpos($key, '|')) {
list($a, $val) = explode('|', $key);
$item[$pk] = $val;
} else {
$item[$pk] = $data;
}
$data = $item;
}
}
$options['data'] = $data;
// 事件回调
if ($result = $this->trigger('before_find', $options)) {
} else {
// 执行查询
$resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
if ($resultSet instanceof \PDOStatement) {
// 返回PDOStatement对象
return $resultSet;
}
$result = isset($resultSet[0]) ? $resultSet[0] : null;
}
if (isset($cache) && false !== $result) {
// 缓存数据
$this->cacheData($key, $result, $cache);
}
}
// 数据处理
if (!empty($result)) {
if (!empty($this->model)) {
// 返回模型对象
$model = $this->model;
$result = new $model($result);
$result->isUpdate(true, isset($options['where']['AND']) ? $options['where']['AND'] : null);
// 关联查询
if (!empty($options['relation'])) {
$result->relationQuery($options['relation']);
}
// 预载入查询
if (!empty($options['with'])) {
$result->eagerlyResult($result, $options['with']);
}
// 关联统计
if (!empty($options['with_count'])) {
$result->relationCount($result, $options['with_count']);
}
}
} elseif (!empty($options['fail'])) {
$this->throwNotFound($options);
}
return $result;
}
~~~