2016-11-04 49 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问题。