Yii2 - ActiveRecord with relations to array -
i know there answer use asarray().
if need model relation , array @ same time?
in example demojson without relations:
$demo = demo::find()->with('bundles')->one(); // view <?= var demojson = json_encode($demo) ?> <!-- using array error --> <?= $demo->bundles[0]->somefunc() ?> <!-- using model ok -->
in example there no somefunc() because simple array used:
$demo = demo::find()->with('bundles')->asarray()->one(); // view <?= var demojson = json_encode($demo) ?> <!-- using array ok --> <?= $demo['bundles'][0]->somefunc() ?> <!-- using model error -->
so, how array model relations without using asarray.
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 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 $bundle) { $bundles[] = $bundle->toarray(); } return $bundles; } return $fields; } }
Comments
Post a Comment