Yii2: ActiveQuery::asArray() return integer as string

Created on 6 Aug 2015  路  4Comments  路  Source: yiisoft/yii2

is this a bug? this is what return when I used asArray()

if you look at the id and backdrop values you'll see that they are strings in the first array, and integers in the second array

$Tour = Tour::find()->asArray()->one();

[
    'id' => '1'
    'title' => 'Lorem ipsum dolor sit amet'
    'content' => 'lorem ipsm dola'
    'placement' => 'right'
    'element' => '#start-tour'
    'path' => '/site/dashboard'
    'duration' => '1000'
    'backdrop' => '1'
    'created_at' => '2015-08-06 05:04:36'
    'updated_at' => '2015-08-06 05:04:36'
]

I can solved this problem by using ArrayHelper::toArray()

$Tour = ArrayHelper::toArray(Tour::find()->one());

[
    'id' => 1
    'title' => 'Lorem ipsum dolor sit amet'
    'content' => 'lorem ipsm dola'
    'placement' => 'right'
    'element' => '#start-tour'
    'path' => '/site/dashboard'
    'duration' => 1000
    'backdrop' => 1
    'created_at' => '2015-08-06 05:04:36'
    'updated_at' => '2015-08-06 05:04:36'
]

Most helpful comment

Typecasting is performed at ActiveRecord level, while asArray option bypasses its usage - otherwise it will not save performance.

The only option will be:

$itemsAsArray = ArrayHelper::toArray(Item::find()->all());

All 4 comments

this is expected:

Note: While this method saves memory and improves performance, it is closer to the lower DB abstraction layer and you will lose most of the Active Record features. A very important distinction lies in the data type of the column values. When you return data in Active Record instances, column values will be automatically typecast according to the actual column types; on the other hand when you return data in arrays, column values will be strings (since they are the result of PDO without any processing), regardless their actual column types.

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#retrieving-data-in-arrays

you can even get that response by using $Tour = Tour::find()->one(); instead of $Tour = ArrayHelper::toArray(Tour::find()->one()); but it has one issue it works fine only for single table if you have join with multiple tables it will only return single table fields it will skip other joined tables field dont know why it might be a bug.

it could be an idea to install an option in which the user can choose for the type hinting to be active

Typecasting is performed at ActiveRecord level, while asArray option bypasses its usage - otherwise it will not save performance.

The only option will be:

$itemsAsArray = ArrayHelper::toArray(Item::find()->all());
Was this page helpful?
0 / 5 - 0 ratings

Related issues

cebe picture cebe  路  53Comments

alexraputa picture alexraputa  路  53Comments

spiritdead picture spiritdead  路  67Comments

deecode picture deecode  路  50Comments

dhiman252 picture dhiman252  路  44Comments