holden321
holden321

Reputation: 1183

Yii2 - ActiveRecord with relations to array

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.

Upvotes: 0

Views: 2981

Answers (1)

Paul
Paul

Reputation: 1657

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;
    }
}

Upvotes: 1

Related Questions