Yii2.0自增主键查询老是字符串的原因剖析

【项目背景】

最近在做一个restful风格的项目,发现有个表返回的json数据中id始终是string类型,但另一个表的id始终是int类型。即返回的数据类型不一致。

 

【原因剖析】

在yii\db\Schema类的getColumnPhpType函数中,这个函数决定了最终出来的数据的类型,代码如下:

    /**
     * Extracts the PHP type from abstract DB type.
     * @param ColumnSchema $column the column schema information
     * @return string PHP type name
     */
    protected function getColumnPhpType($column)
    {
        static $typeMap = [
            // abstract type => php type
            self::TYPE_TINYINT => 'integer',
            self::TYPE_SMALLINT => 'integer',
            self::TYPE_INTEGER => 'integer',
            self::TYPE_BIGINT => 'integer',
            self::TYPE_BOOLEAN => 'boolean',
            self::TYPE_FLOAT => 'double',
            self::TYPE_DOUBLE => 'double',
            self::TYPE_BINARY => 'resource',
            self::TYPE_JSON => 'array',
        ];
        if (isset($typeMap[$column->type])) {
            if ($column->type === 'bigint') {
                return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string'; // 这里决定字段类型
            } elseif ($column->type === 'integer') {
                return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer'; // 这里决定字段类型
            }

            return $typeMap[$column->type];
        }

        return 'string';
    }

结论:如果PHP_INT_SIZE是4并且DB表中对应的列是无符号整形的话就返回string类型.按照php.net上的解释:PHP 不支持无符号整数。

 

 

posted @ 2020-02-08 12:22  冰狼爱魔  阅读(408)  评论(0编辑  收藏  举报