Alliswell Alliswell - 1 year ago 215
PHP Question

Yii2 ArrayHelper::toArray doesn't work recursively

Yii2 ArrayHelper's helper method toArray doesn't convert nested objects.

Here is my test code.

public function actionTest()
$product = \common\models\Product::find()
->where(['id' => 5779])

$product = \yii\helpers\ArrayHelper::toArray($product);


Recursive property is enabled by default.

public static array toArray ( $object, $properties = [], $recursive =

So this piece of code should work correctly but it doesn't.

Action returns one level array without

What I'm doing wrong here?

Code was simplified for test purposes. I know that in this certain situation one can simply use
method to get AR record in array.

Answer Source

You should use this instead :

$product = \common\models\Product::find()
    ->where(['id' => 5779])

Read more.

EDIT : And if your really want to use toArray(), and since a relation is not really an attribute or property, you should simply use the second parameter, e.g. :

$product = \yii\helpers\ArrayHelper::toArray($product, [
    'common\models\Product' => [
        // add needed properties here
        // ...