Laravel 提供了 Eager Loading使用 with()方法來緩解 N+1 的問題,但是在實際使用中還是存在一些問題的, with()會直接查詢出表中所有的欄位,而我們可能僅僅需要其中指定的某幾個欄位。
假如我們現在有兩張表: user和 posts,每個 User 可以擁有多個 Posts,而每一篇 Post 只能屬於一個 User。下面分別是 User Model 和 Post Model 中定義的關係:
// User.php public function post(){ return $this->hasMany('post');}// Post.phppublic function user(){ return $this->belongsTo('user');}
通過 with()方法,我們可以這樣擷取所有的 Posts 並同時查出對應的 User 資訊,可以使用這樣的方法:
public function getAllPosts() { return Post::with('user')->get();}
這實際上會執行下面兩句 SQL 陳述式:
select * from `posts`select * from `users` where `users`.`id` in (<1>, <2>)
但是我們可能並不需要 User 表中所有的欄位,例如我們只需要 id和 username兩個欄位:
select * from `posts`select id,username from `users` where `users`.`id` in (<1>, <2>)
我們可以通過下面兩種方法來實現。
方法一:在 with() 中指定
Post::with(array('user'=>function($query){ $query->select('id','username');}))->get();
方法二:修改 Model 檔案
修改 Post.php 檔案中 user() 方法:
public function user(){ return $this->belongsTo('User')->select(array('id', 'username'));}