E
E
Evgeny Akhmetov2018-03-29 15:29:06
Yii
Evgeny Akhmetov, 2018-03-29 15:29:06

How to add related model to ArrayHelper::toArray()?

There was a problem, you need to give data with related data in the model with getters:
If you do it through asArray ()

return Project::find()->with(['group', 'userShare', 'userShare.profile', 'author'])->where(['id' => $id])->asArray()->one();

Everything is fine, all the data comes.
For inArray:
$project = Project::find()->with(['group', 'userShare', 'userShare.profile', 'author'])->where(['id' => $id])->one();
return $project->toArray([], ['group', 'userShare', 'userShare.profile', 'author']);

The userShare.profile object does not come, a question for connoisseurs, is it possible to get it somehow?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-03-29
@asperin2

configure the returned fields, you can read more here

E
Evgeny Akhmetov, 2018-03-29
@asperin2

Thank you, everything worked out, I'll leave the solution here, suddenly it will be useful to someone:

$project = Project::find()->with(['group', 'userShare', 'author'])->where(['id' => $id])->one();
        return ArrayHelper::toArray($project, ['app\models\Project' => array_merge($project->fields(), ['group',
            'userShare' => function ($project) {
                $share = $project->userShare;
                $share = array_map(function($elem) {
                    $elem->profile = $elem->profileq;
                    return $elem;
                }, $share);
                return $share;
            },
            'author'])]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question