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) {[...]