配置

// 数据库配置
//mysql
// think\db\cconnector\Mysql
protected function parseDsn($config)
{
    if (!empty($config['socket'])) {
        $dsn = 'mysql:unix_socket=' . $config['socket'];
    } elseif (!empty($config['hostport'])) {
        $dsn = 'mysql:host=' . $config['hostname'] . ';port=' . $config['hostport'];
    } else {
        $dsn = 'mysql:host=' . $config['hostname'];
    }
    $dsn .= ';dbname=' . $config['database'];

    if (!empty($config['charset'])) {
        $dsn .= ';charset=' . $config['charset'];
    }

    return $dsn;
}
// sqlsrv
// think\db\connector\Sqlsrv
protected function parseDsn($config)
{
    $dsn = 'sqlsrv:Database=' . $config['database'] . ';Server=' . $config['hostname'];

    if (!empty($config['hostport'])) {
        $dsn .= ',' . $config['hostport'];
    }

    return $dsn;
}

连接

// 连接连接
// think\db\Connection
$pdo=new PDO($config['dsn'], $config['username'], $config['password'], $params);

组装语句


// think\db\Builider
/**
 * 生成查询SQL
 * @access public
 * @param  Query  $query  查询对象
 * @return string
 */
public function select(Query $query)
{
    $options = $query->getOptions();

    return str_replace(
        ['%TABLE%', '%DISTINCT%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
        [
            $this->parseTable($query, $options['table']),
            $this->parseDistinct($query, $options['distinct']),
            $this->parseField($query, $options['field']),
            $this->parseJoin($query, $options['join']),
            $this->parseWhere($query, $options['where']),
            $this->parseGroup($query, $options['group']),
            $this->parseHaving($query, $options['having']),
            $this->parseOrder($query, $options['order']),
            $this->parseLimit($query, $options['limit']),
            $this->parseUnion($query, $options['union']),
            $this->parseLock($query, $options['lock']),
            $this->parseComment($query, $options['comment']),
            $this->parseForce($query, $options['force']),
        ],
        $this->selectSql);
}

执行查询

// think\db\Connection
/**
 * 执行查询 返回数据集
 * @access public
 * @param  string    $sql sql指令
 * @param  array     $bind 参数绑定
 * @param  bool      $master 是否在主服务器读操作
 * @param  bool      $pdo 是否返回PDO对象
 * @return array
 * @throws BindParamException
 * @throws \PDOException
 * @throws \Exception
 * @throws \Throwable
 */
public function query($sql, $bind = [], $master = false, $pdo = false)
{
    $this->initConnect($master);

    if (!$this->linkID) {
        return false;
    }

    // 记录SQL语句
    $this->queryStr = $sql;

    $this->bind = $bind;

    Db::$queryTimes++;

    try {
        // 调试开始
        $this->debug(true);

        // 预处理
        $this->PDOStatement = $this->linkID->prepare($sql);

        // 是否为存储过程调用
        $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);

        // 参数绑定
        if ($procedure) {
            $this->bindParam($bind);
        } else {
            $this->bindValue($bind);
        }

        // 执行查询
        $this->PDOStatement->execute();

        // 调试结束
        $this->debug(false, '', $master);

        // 返回结果集
        return $this->getResult($pdo, $procedure);
    } catch (\PDOException $e) {
        if ($this->isBreak($e)) {
            return $this->close()->query($sql, $bind, $master, $pdo);
        }

        throw new PDOException($e, $this->config, $this->getLastsql());
    } catch (\Throwable $e) {
        if ($this->isBreak($e)) {
            return $this->close()->query($sql, $bind, $master, $pdo);
        }

        throw $e;
    } catch (\Exception $e) {
        if ($this->isBreak($e)) {
            return $this->close()->query($sql, $bind, $master, $pdo);
        }

        throw $e;
    }
}

查询结果转换

// think\Model
/**
 * 转换当前模型对象为数组
 * @access public
 * @return array
 */
public function toArray()
{
    $item       = [];
    $hasVisible = false;

    foreach ($this->visible as $key => $val) {
        if (is_string($val)) {
            if (strpos($val, '.')) {
                list($relation, $name)      = explode('.', $val);
                $this->visible[$relation][] = $name;
            } else {
                $this->visible[$val] = true;
                $hasVisible          = true;
            }
            unset($this->visible[$key]);
        }
    }

    foreach ($this->hidden as $key => $val) {
        if (is_string($val)) {
            if (strpos($val, '.')) {
                list($relation, $name)     = explode('.', $val);
                $this->hidden[$relation][] = $name;
            } else {
                $this->hidden[$val] = true;
            }
            unset($this->hidden[$key]);
        }
    }

    // 合并关联数据
    $data = array_merge($this->data, $this->relation);

    foreach ($data as $key => $val) {
        if ($val instanceof Model || $val instanceof ModelCollection) {
            // 关联模型对象
            if (isset($this->visible[$key]) && is_array($this->visible[$key])) {
                $val->visible($this->visible[$key]);
            } elseif (isset($this->hidden[$key]) && is_array($this->hidden[$key])) {
                $val->hidden($this->hidden[$key]);
            }
            // 关联模型对象
            if (!isset($this->hidden[$key]) || true !== $this->hidden[$key]) {
                $item[$key] = $val->toArray();
            }
        } elseif (isset($this->visible[$key])) {
            $item[$key] = $this->getAttr($key);
        } elseif (!isset($this->hidden[$key]) && !$hasVisible) {
            $item[$key] = $this->getAttr($key);
        }
    }

    // 追加属性(必须定义获取器)
    if (!empty($this->append)) {
        foreach ($this->append as $key => $name) {
            if (is_array($name)) {
                // 追加关联对象属性
                $relation = $this->getRelation($key);

                if (!$relation) {
                    $relation = $this->getAttr($key);
                    if ($relation) {
                        $relation->visible($name);
                    }
                }

                $item[$key] = $relation ? $relation->append($name)->toArray() : [];
            } elseif (strpos($name, '.')) {
                list($key, $attr) = explode('.', $name);
                // 追加关联对象属性
                $relation = $this->getRelation($key);

                if (!$relation) {
                    $relation = $this->getAttr($key);
                    if ($relation) {
                        $relation->visible([$attr]);
                    }
                }

                $item[$key] = $relation ? $relation->append([$attr])->toArray() : [];
            } else {
                $item[$name] = $this->getAttr($name, $item);
            }
        }
    }

    return $item;
}

本文由 yang 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

楼主残忍的关闭了评论