0

I know there is the answer to use asArray().
But what if I need model from relation and array at the same time?

In this example demoJson is without relations:

$demo = Demo::find()->with('bundles')->one();

// view
<?= var demoJson = json_encode($demo) ?> <!-- Using as array ERROR -->
<?= $demo->bundles[0]->someFunc() ?> <!-- Using model OK -->


In this example there is no someFunc() because a simple array used:

$demo = Demo::find()->with('bundles')->asArray()->one();

// view
<?= var demoJson = json_encode($demo) ?> <!-- Using as array OK -->
<?= $demo['bundles'][0]->someFunc() ?> <!-- Using model ERROR -->


So, how to get array from model with all its relations but without using asArray.

1 Answer 1

1

You might try:

$demo = Demo::find()->with('bundles')->limit(1)->one();

// view
<?= var demoJson = json_encode($demo->toArray()) ?>
<?= $demo->bundles[0]->someFunc() ?>

The Demo model could be this:

namespace app\models;

use yii\db\ActiveRecord;

Class Demo extends ActiveRecord
{
    // ...

    /**
     * @return array
     */
    public function fields()
    {
        $fields = parent::fields();

        if ($this->isNewRecord) {
            return $fields;
        }

        $fields['bundles'] = function() {
            $bundles = [];

            foreach ($this->bundles as $bundle) {
                $bundles[] = $bundle->toArray();
            }

            return $bundles;
        }

        return $fields;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

$demo->toArray() is without data from relations (like in Example 1)
@holden321 You have to rewrite the fields function in your Demo model. My computer just gong down, I would like to post my answer at a later time.
@holden321 I have edited my answer. If there are somethings wrong, please let me know.

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.