2016-11-04 52 views
0

如果我沒有弄錯,急切加載的目的是減少數據庫查詢的數量。但是,如果我下面添加到我的查詢生成器的實例,它會爲每個記錄額外的SQL查詢返回:Eager loading不能正常工作

 ->with([ 
      'firstEarmark' => function($q) { 
       $q 
       ->select('earmarks.*') 
       ->join('locations', 'locations.id', '=', 'earmarks.location') 
       ->select('earmarks.*', 'locations.location AS earmarked_location') 
       ->where('date', '>=', date('m/d/Y'))->orderBy('date', 'asc') 
       ->get(); 
      } 

它這樣做是有或無連接語句。

所以我錯過了急於加載的點,還是我做錯了?

我的第二個(稍微不相關的)問題是,如果我包含註釋 - > select()語句,則由於某種原因,此子查詢不會生成任何結果。

事實上,Laravel正在爲每條記錄生成相同的SQL查詢。如果有兩個筆記本電腦的結果,我得到兩個相同的查詢拉第一撥出記錄每個:

 113 Prepare select `earmarks`.*, `locations`.`location` as `earmarked_location` from `earmarks` inner join `locations` on `locations`.`id` = `earmarks`.`location` where `earmarks`.`laptop_id` in (?, ?) and `date` >= ? order by `date` asc 
     113 Execute select `earmarks`.*, `locations`.`location` as `earmarked_location` from `earmarks` inner join `locations` on `locations`.`id` = `earmarks`.`location` where `earmarks`.`laptop_id` in (1, 2) and `date` >= '11/04/2016' order by `date` asc 
     113 Close stmt  
     113 Prepare select `earmarks`.*, `locations`.`location` as `earmarked_location` from `earmarks` inner join `locations` on `locations`.`id` = `earmarks`.`location` where `earmarks`.`laptop_id` in (?, ?) and `date` >= ? order by `date` asc 
     113 Execute select `earmarks`.*, `locations`.`location` as `earmarked_location` from `earmarks` inner join `locations` on `locations`.`id` = `earmarks`.`location` where `earmarks`.`laptop_id` in (1, 2) and `date` >= '11/04/2016' order by `date` asc 

這些查詢是相同的!

回答

1

由於執行它的子查詢的末尾有get(),因此會生成多個查詢。您不會在Laravel中執行子查詢,因爲它們將在第一個查詢運行以附加關係後執行。用take(1)代替,機智將解決您的N + 1問題。