Think\Db\Query::column PHP 메소드

column() 공개 메소드

得到某个列的数组
public column ( string $field, string $key = '' ) : array
$field string 字段名 多个字段用逗号分隔
$key string 索引
리턴 array
    public function column($field, $key = '')
    {
        $result = false;
        if (!empty($this->options['cache'])) {
            // 判断查询缓存
            $cache = $this->options['cache'];
            if (empty($this->options['table'])) {
                $this->options['table'] = $this->getTable();
            }
            $guid = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($this->options));
            $result = Cache::get($guid);
        }
        if (false === $result) {
            if (isset($this->options['field'])) {
                unset($this->options['field']);
            }
            if ($key && '*' != $field) {
                $field = $key . ',' . $field;
            }
            $pdo = $this->field($field)->fetchPdo(true)->select();
            if (is_string($pdo)) {
                // 返回SQL语句
                return $pdo;
            }
            if (1 == $pdo->columnCount()) {
                $result = $pdo->fetchAll(PDO::FETCH_COLUMN);
            } else {
                $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC);
                if ($resultSet) {
                    $fields = array_keys($resultSet[0]);
                    $count = count($fields);
                    $key1 = array_shift($fields);
                    $key2 = $fields ? array_shift($fields) : '';
                    $key = $key ?: $key1;
                    foreach ($resultSet as $val) {
                        if ($count > 2) {
                            $result[$val[$key]] = $val;
                        } elseif (2 == $count) {
                            $result[$val[$key]] = $val[$key2];
                        } elseif (1 == $count) {
                            $result[$val[$key]] = $val[$key1];
                        }
                    }
                } else {
                    $result = [];
                }
            }
            if (isset($cache) && isset($guid)) {
                // 缓存数据
                if (isset($cache['tag'])) {
                    Cache::tag($cache['tag'])->set($guid, $result, $cache['expire']);
                } else {
                    Cache::set($guid, $result, $cache['expire']);
                }
            }
        } else {
            // 清空查询条件
            $this->options = [];
        }
        return $result;
    }