Think\Db\Query::getTableInfo PHP Method

getTableInfo() public method

获取数据表信息
public getTableInfo ( mixed $tableName = '', string $fetch = '' ) : mixed
$tableName mixed 数据表名 留空自动获取
$fetch string 获取信息类型 包括 fields type bind pk
return mixed
    public function getTableInfo($tableName = '', $fetch = '')
    {
        if (!$tableName) {
            $tableName = $this->getTable();
        }
        if (is_array($tableName)) {
            $tableName = key($tableName) ?: current($tableName);
        }
        if (strpos($tableName, ',')) {
            // 多表不获取字段信息
            return false;
        } else {
            $tableName = $this->parseSqlTable($tableName);
        }
        list($guid) = explode(' ', $tableName);
        if (!isset(self::$info[$guid])) {
            if (!strpos($guid, '.')) {
                $schema = $this->getConfig('database') . '.' . $guid;
            } else {
                $schema = $guid;
            }
            // 读取缓存
            if (is_file(RUNTIME_PATH . 'schema/' . $schema . '.php')) {
                $info = (include RUNTIME_PATH . 'schema/' . $schema . '.php');
            } else {
                $info = $this->connection->getFields($guid);
            }
            $fields = array_keys($info);
            $bind = $type = [];
            foreach ($info as $key => $val) {
                // 记录字段类型
                $type[$key] = $val['type'];
                $bind[$key] = $this->getFieldBindType($val['type']);
                if (!empty($val['primary'])) {
                    $pk[] = $key;
                }
            }
            if (isset($pk)) {
                // 设置主键
                $pk = count($pk) > 1 ? $pk : $pk[0];
            } else {
                $pk = null;
            }
            self::$info[$guid] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk];
        }
        return $fetch ? self::$info[$guid][$fetch] : self::$info[$guid];
    }

Usage Example

Example #1
0
 /**
  * 获取关联模型的字段 并解决混淆
  * @access protected
  * @param \think\db\Query   $query 查询对象
  * @param string            $name 模型名称
  * @param string            $table 关联表名称
  * @param array             $map 字段映射
  * @param array             $fields 查询字段
  * @return array
  */
 protected static function getModelField($query, $name, $table = '', $map = [], $fields = [])
 {
     // 获取模型的字段信息
     $fields = $fields ?: $query->getTableInfo($table, 'fields');
     $array = [];
     foreach ($fields as $field) {
         if ($key = array_search($name . '.' . $field, $map)) {
             // 需要处理映射字段
             $array[] = $name . '.' . $field . ' AS ' . $key;
         } else {
             $array[] = $field;
         }
     }
     return $array;
 }