2016-11-04 11 views
0

私が間違っていないと、熱心な読み込みの目的はDBクエリの数を減らすことです。Eager loading does not working

 ->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(); 
      } 

をそれが結合文の有無にかかわらず、この処理を行います。私は、クエリビルダインスタンスに以下を追加した場合でも、それは各レコードの追加のSQLクエリが返さ生成します。

私は熱心な読み込みのポイントを見逃していますか、それとも間違っていますか?

私の2番目の(わずかに関係のない)問題は、コメント付きの - > select()文を含めると何らかの理由で結果が得られないということです。

実際、Laravelはレコードごとに同じSQLクエリを生成しています。 2つのラップトップの結果がある場合、それぞれの最初のEarmarkレコードを取得する2つの同一のクエリが得られます。

 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の問題が解決します。

関連する問題