Laravel Eager Loading & Lazy Loading(急切載入與惰性載入)

Mattsuyolo
3 min readJul 19, 2020

--

參考來源文件(Reference) :

https://stackoverflow.com/questions/31366236/lazy-loading-vs-eager-loading

說明:

Eager Loading(急切載入)用於解決N+1 的問題,Laravel Eloquent預設機制為Lazy Loading, 文件以書與作者關聯來解釋,以下以電影與導演的關聯來說明。 讀者可以自行想一個情境幫助自我理解

範例:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
/**
* Get the director that direct the movie.
*/
public function director()
{
return $this->belongsTo('App\Director');
}
}

現在如果要取得所有電影的導演名稱

$movies = App\Movie::all();

foreach ($movies as $movie) {
echo $movie->director->name;
}

這樣的寫法會執行一個查詢取出所有的影片,並迴圈取出關聯的導演名稱,如果有30部電影,會有1+30筆對資料庫的查詢;

藉由Eager Loading “with” 的語法,只會使用兩筆查詢

$movies = App\Movie::with('director')->get();

foreach ($movies as $movie) {
echo $movie->director->name;
}

Sql 語法

select * from movies

select * from directors where id in (1, 2, 3, 4, 5, ...)

若你需要一次取出多個關聯,增加參數在with後即可

$movies = App\Movie::with(['director', 'category'])->get();

簡單使用時機判別:

Eager Loading(急切加載): 用於你的關聯很少時或是主機與Sql間的Ping 值很高。

Lazy Loading (延遲加載):你的資源關聯非常多,且你不需要即時獲得關聯的資源。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mattsuyolo
Mattsuyolo

Written by Mattsuyolo

The greats never sacrifice the important for the urgent

No responses yet

Write a response