Difference between #9 and #10 of
Relational Query - Lazy Loading and Eager Loading in Yii 2.0

Revision #10 has been created by samdark on Jun 22, 2019, 8:36:55 AM with the memo:

Fixed typo in title
« previous (#9)

Changes

Title changed

Relational Query - Lazy Loadning and Eager Loading in Yii 2.0

Category unchanged

Tutorials

Yii version changed

2.0

Tags changed

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

Content changed

[...]
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) {
[...]
10 0
6 followers
Viewed: 58 564 times
Version: 2.0
Category: Tutorials
Written by: softark
Last updated by: samdark
Created on: Jan 9, 2016
Last updated: 5 years ago
Update Article

Revisions

View all history