Answer the question
In order to leave comments, you need to log in
How to get related data in Active Record Yii2?
Let's assume there are tables posts and comments connected among themselves one-to-many. (comments.post_id->post.id)
In Laravel, I can get related data by calling one method:
$post = Post::find()
->with('comments')
->all();
[
0 => [
'id' => 1,
'title' => 'Some Title',
'comments' => [
0 => [
'id' => 1,
'comment' => 'Some comment text',
],
1 => [
'id' => 2,
'comment' => 'Another comment text',
]
...
]
]
1 => [
'id' => 2,
'title' => 'Another Title',
'comments' => [
0 => [
'id' => 3,
'comment' => 'Some comment text',
],
1 => [
'id' => 4,
'comment' => 'Another comment text',
]
...
]
]
...
]
$post = Post::find()
->with('comments')
->all();
Answer the question
In order to leave comments, you need to log in
use geth. in the Post model add for example:
public function getComments(){
return $this->hasMany(Comments::className(), ['post_id' => 'id']);
}
Are you interested in eager loading?
Use the method you wrote.
$post = Post::find()
->with('comments')
->all();
At the same time, read in the docks how eager loading works in yii2, here zelenin unsubscribes:
www.yiiframework.ru/forum/viewtopic.php?t=22879
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question