/** * 查找记录 * @access public * @param array|string|Query|\Closure $data * @return Collection|false|\PDOStatement|string * @throws DbException * @throws ModelNotFoundException * @throws DataNotFoundException */ public function select($data = null) { if ($data instanceof Query) { return $data->select(); } elseif ($data instanceof \Closure) { call_user_func_array($data, [&$this]); $data = null; } // 分析查询表达式 $options = $this->parseExpress(); if (false === $data) { // 用于子查询 不查询只返回SQL $options['fetch_sql'] = true; } elseif (!is_null($data)) { // 主键条件分析 $this->parsePkWhere($data, $options); } $resultSet = false; if (empty($options['fetch_sql']) && !empty($options['cache'])) { // 判断查询缓存 $cache = $options['cache']; unset($options['cache']); $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options)); $resultSet = Cache::get($key); } if (!$resultSet) { // 生成查询SQL $sql = $this->builder()->select($options); // 获取参数绑定 $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 return $this->connection->getRealSql($sql, $bind); } // 执行查询操作 $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_class']); if ($resultSet instanceof \PDOStatement) { // 返回PDOStatement对象 return $resultSet; } if (isset($cache)) { // 缓存数据集 if (isset($cache['tag'])) { Cache::tag($cache['tag'])->set($key, $resultSet, $cache['expire']); } else { Cache::set($key, $resultSet, $cache['expire']); } } } // 返回结果处理 if (count($resultSet) > 0) { // 数据列表读取后的处理 if (!empty($this->model)) { // 生成模型对象 $model = $this->model; foreach ($resultSet as $key => $result) { /** @var Model $result */ $result = new $model($result); $result->isUpdate(true); // 关联查询 if (!empty($options['relation'])) { $result->relationQuery($options['relation']); } $resultSet[$key] = $result; } if (!empty($options['with']) && $result instanceof Model) { // 预载入 $resultSet = $result->eagerlyResultSet($resultSet, $options['with'], is_object($resultSet) ? get_class($resultSet) : ''); } } } elseif (!empty($options['fail'])) { $this->throwNotFound($options); } return $resultSet; }