# Laravel Eager Loading 解決資料庫 N+1 查詢問題 在實作查看購物車中商品功能時,原本要取得購物車所有商品時,會產生多筆 SQL 查詢,如: *app/Http/Controllers/CartController.php* ```php= . . . public function index(Request $request) { $cartItems = $request->user()->cartItems()->get(); return view('cart.index', ['cartItems' => $cartItems]); } ``` 而資料筆數一多就會有 N+1 問題,導致網站效能不佳,這時候就可以加入 with(): ```php= public function index(Request $request) { $cartItems = $request->user()->cartItems()->with(['productSku.product'])->get(); return view('cart.index', ['cartItems' => $cartItems]); } ``` 透過 with() 就能一次把關聯的資料取得到了,可以大幅改善效能問題,差別大概是像這樣: ```sql= select * from books select * from authors where id in (1, 2, 3, 4, 5, ...) ``` 而在 with() 中使用 "." 就能表示多層級巢狀關聯的關係 (Nested Relationship) 喔 ###### tags: `Laravel` `MySQL`