Answer the question
In order to leave comments, you need to log in
How to make Yii2 get all fields from relationships?
So, given:
* There is a model A, with a specific hasOne relationship to model B. The usual belonging to a specific author.
* There is a REST-endpoint to which the client will come and expect to receive such JSON:
{
success: true,
code: 200,
data: [{
id: 1, // <- From table A
title: "TESTTESTTEST", // <- From table A
description: "LONGTESTDESCRIPTION", // <- From table A
username: "IvanBEST" // <- From table B and from field "username"
},
{
id: 2, // <- From table A
title: "Post #777", // <- From table A
description: "Lorem ipsum...", // <- From table A
username: "Oleg222" // <- From table B and from field "username"
},
{
...
}
]
}
public function actionIndex()
{
return MyModel::find()->with(['author'])->all();
}
{
"success": true,
"code": 200,
"data": [
{
"id": 1,
"title": "Faker id5975f7355e568",
"description": "Voluptas cum incidunt et enim...",
"author_id": 1, // <--
"image_id": 1,
"parent_id": null,
"created_at": "2017-07-24 16:33:41",
},
{
"id": 2,
"title": "Faker id5975f7357aa18",
"description": "Eum dolores eum maxime quos...",
"author_id": null, // <-- ТУТ ясно
"image_id": 1,
"parent_id": null,
"created_at": "2017-07-24 16:33:41",
},
]
}
return Quest::find()->select(['id', 'title', 'description', 'author.username'])->with(['author'])->all();
return Quest::find()->alias('t')->select(['t.id', 't.title', 't.description', 'author.username'])->innerJoinWith(['author author'])->all();
SELECT `t`.`id`, `t`.`title`, `t`.`description`, `author`.`username` FROM `tb__quest` `t` INNER JOIN `tb__user` `author` ON `t`.`author_id` = `author`.`id`
{
"id": 1,
"title": "Faker id5975f7355e568",
"description": "Voluptas cum incidunt et enim..."
},
{
"id": 2,
"title": "Faker id5975f735a8923",
"description": "Eum delectus quis vero laborum ab..."
},
Answer the question
In order to leave comments, you need to log in
If I understand you correctly, then instead ->with
of->joinWith
return Quest::find()->select(['id', 'title', 'description', 'author.username'])->joinWith(['author'])->all();
Add to the model
AND specify in the request
->select(['t.id', 't.title', 't.description', 'author.username as "authorName"'])
How is the relationship described? In fact, the author should have returned an object, but not an id
EDITED: you have an array in with, but it should just be a stringwith('author')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question