How to pass model to JSON

If a have a model build from a hasMany relationship, how can I export it as an array of value so it can be returned as part of

$modelLeg = ProjectsLegs::findOne(['LegId' => $id]);
$modelInvoicesItems = $modelLeg->projectsLegsInvoicesItems;

return json_encode([
    'modelInvoicesItems' => $modelInvoicesItems
 ]);

so in the beforesubmit JS code I can retrieve it an display it in the console for troubleshooting purposes?

If I use the above I get modelInvoicesItems: Array(3) [{}, {}, {}]

For a single element model I can simple use ->attributes, but how can I perform the same breakdown on an models of many elements?

I have been using

foreach ($modelInvoicesItems as $k => $v) {
    $debugger['modelInvoicesItems'][$k] = $v->attributes;
}

return json_encode([
    'modelInvoicesItems' => $debugger
 ]);

and it works, but wondering if Yii has function for this type of thing specifically?

Hm, you probably want to use Serializer like REST API. https://www.yiiframework.com/doc/guide/2.0/en/rest-response-formatting
?

Use the ->asArray() method with the find search (not the findOne):

$modelLeg = ProjectsLegs::find(['LegId' => $id])->asArray()->one();

@bpanatta it should be:

$modelLeg = ProjectsLegs::find()->where(['LegId' => $id])->asArray()->one();

https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord#find()-detail

1 Like