Alliswell Alliswell - 5 months ago 63
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])
->with('firstImage')
->one();

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

print_r($product);
}


Recursive property is enabled by default.


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


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

Action returns one level array without
firstImage
object.

What I'm doing wrong here?

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

Answer

You should use this instead :

$product = \common\models\Product::find()
    ->where(['id' => 5779])
    ->with('firstImage')
    ->asArray()
    ->one();

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
        // ...
        'firstImage',
    ],
]);