D
D
DieZz2015-12-18 07:20:01
Yii
DieZz, 2015-12-18 07:20:01

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

As a result, if I display the posts as an array, I will get something like this:
[
  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',
      ]
      ...
    ]
  ]
  ...
]

In yii, using eager loading, you can do something like this
$post = Post::find()
    ->with('comments')
    ->all();

but there will be no comments in the output array.
Is it possible to do something similar in YII as in the Laravel example above?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2015-12-18
@Raz-Mik

use geth. in the Post model add for example:

public function getComments(){
        return $this->hasMany(Comments::className(), ['post_id' => 'id']);
}

D
Dmitry Bay, 2015-12-18
@kawabanga

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 question

Ask a Question

731 491 924 answers to any question