Relational Query - Lazy Loading and Eager Loading in Yii 2.0

Comparing #9 with #10

Revision #10 was created by samdark samdark on Jun 22, 2019, 8:36:55 AM.

Fixed typo in title

Title

Relational Query - Lazy Loadning and Eager Loading in Yii 2.0

Yii version

2.0

Tags

relational query, lazyeager loading, eagerlazy loading, with, join, joinWith

Content

[...]
In the following sections, we assume an example of 1:N relation like this:

- An Author has_many Posts


```php

/* Author.php */
public function getPosts()
[...]
- A Post has_one Author


```php

/* Post.php */
public function getAuthor()
[...]
The following is an example of lazy loading.


```php

$authors = Author::find()->all(); // fetches only the authors
foreach($authors as $author) {
[...]
The following is an example of eager loading.


```php

$authors = Author::find()->with('posts')->all(); // fetches the authors with their posts
foreach($authors as $author) {
[...]
Imagine you wanted to list 10 authors with their posts. You would write like this:


```php

$authors = Author::find()->with('posts')->limit(10)->all();
```
[...]
For example, when you want to list authors who have at least one post with a title containing some key word, you can write like the following using 'leftJoin':


```php

$authors = Author::find()
->leftJoin('post', ['post.author_id' => 'author.id']) // the table name and the condition for 'ON'
[...]
So, probably you may want to use 'joinWith' like the following:


```php

$authors = Author::find()
->joinWith('posts') // the relation name
->where(['like', 'post.title', $keyword])
->all();
foreach($authors as $author) {
[...]