yii2 数据库查询结果字段类型的问题

yii2数据库查询默认返回的为AR对象,此时字段类型与数据库的基本相符,但若是使用 asArray 以数组的方式返回时,默认字段类型全都是 string,若是这样 json_encode 后返回给 App端的话,会被 Android/IOS这些强类型语言端的工程师们喷死,php会再次被推向风口。php

缘由是 pdoyii2盛行时还不够完善,一些特性是后期加进来的,好比咱们急切须要的返回的结果数据类型与数据库一致。mysql

<?php

return [
    'class'       => 'yii\db\Connection',
    'dsn'         => 'mysql:host=localhost;dbname=yii2basic',
    'username'    => 'root',
    'password'    => '123456',
    'charset'     => 'utf8',
    'tablePrefix' => 'yii_',
    'attributes'  => [
        PDO::ATTR_STRINGIFY_FETCHES => false,
        PDO::ATTR_EMULATE_PREPARES  => false,
    ]
    // Schema cache options (for production environment)
    //'enableSchemaCache' => true,
    //'schemaCacheDuration' => 60,
    //'schemaCache' => 'cache',
];

yii2 在数据库组件配置中添加attributes的两项配置便可。sql

未配置时:数据库

// AR 对象的 attributes
array (size=7)
  'id' => string '1' (length=1)
  'account' => string 'big_cat' (length=7)
  'password' => string 'e10adc3949ba59abbe56e057f20f883e' (length=32)
  'age' => int 29
  'created_at' => string '2019-05-16 11:23:26' (length=19)
  'updated_at' => string '2019-05-16 11:23:26' (length=19)
  'status' => int 1

// asArray
array (size=7)
  'id' => string '1' (length=1)
  'account' => string 'big_cat' (length=7)
  'password' => string 'e10adc3949ba59abbe56e057f20f883e' (length=32)
  'age' => string '29' (length=2)
  'created_at' => string '2019-05-16 11:23:26' (length=19)
  'updated_at' => string '2019-05-16 11:23:26' (length=19)
  'status' => string '1' (length=1)

配置后json

// AR 对象的 attributes
array (size=7)
  'id' => string '1' (length=1)
  'account' => string 'big_cat' (length=7)
  'password' => string 'e10adc3949ba59abbe56e057f20f883e' (length=32)
  'age' => int 29
  'created_at' => string '2019-05-16 11:23:26' (length=19)
  'updated_at' => string '2019-05-16 11:23:26' (length=19)
  'status' => int 1

// asArray
array (size=7)
  'id' => int 1
  'account' => string 'big_cat' (length=7)
  'password' => string 'e10adc3949ba59abbe56e057f20f883e' (length=32)
  'age' => int 29
  'created_at' => string '2019-05-16 11:23:26' (length=19)
  'updated_at' => string '2019-05-16 11:23:26' (length=19)
  'status' => int 1

能够发现:
一、AR 对象默认就能将字段类型与数据库中尽量的一致,但id仍是string类型。
二、以数组的方式返回结果时,yii2默认将全部字段都以string方式处理,经过配置pdo属性能彻底的将字段类型同数据库一致。数组

配置pdo属性后查询 AR 对象的话id仍是没有同数据库字段类型一致,但数组方式查询则彻底一致了。yii2

并且数组查询方式更节省内存,性能更高(yii2其实始终以数组模式查询,若是不使用asArray模式,会对查询到的数组结果集结合对应的Model进行映射成相应的AR对象,即asArray实际上是关闭了数组映射至AR对象的步骤,参照),咱们为App提供数据时自己就是要提供一些数据标量,不必查询数据对象,因此接口返回数据时都应该以asArray的方式查询,且配置PDO的属性以便保持数据字段类型的一致性,避免对接上的混乱。yii

相关文章
相关标签/搜索