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.

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();

1 Like