4

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.

0

1 Answer 1

6

You should use this instead :

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

Read more about Retrieving Data in Arrays.

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

Or, if you are using REST, you could override extraFields() in your model :

public function extraFields()
{
    return ['firstImage'];
}

Read more about REST fields.

Sign up to request clarification or add additional context in comments.

5 Comments

I know it. Code was intentionally simplified for test purposes. There are some more complex cases where I need to convert AR object to array. And I need it work recursively.
by this, it needs to add all model properties, it will be lengthy. is there any precise method to do this? so that all models and its related models will come in array.
@FSShaikh no, as far as I understand, you should explicitly specify properties you want to be in the output array.
thanks, but it will increase lines of code in all requests, basically i have to develop REST application that will send response in JSON format.
You should ask another question... Or simply read this : yiiframework.com/doc-2.0/guide-rest-resources.html#fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.