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;
}
~~~