急切加载不工作

时间:2016-11-04 10:47:00

标签: laravel eloquent

如果我没有弄错的话,急切加载的目的是减少数据库查询的数量。但是,如果我将以下内容添加到查询构建器实例中,它会为返回的每条记录生成一个额外的SQL查询:

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

无论是否使用join语句都可以。

所以我错过了急切的加载点,或者我做错了吗?

我的第二个(稍微不相关)问题是,如果我包含注释 - > select()语句,则此子查询由于某种原因不会产生任何结果。

实际上,Laravel正在为每条记录生成相同的SQL查询。如果有两个笔记本电脑的结果,我会得到两个相同的查询来拉取每个的第一个Earmark记录:

      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 个答案:

答案 0 :(得分:1)

它正在生成多个查询,因为您的get()在执行它的子查询的末尾。您不在Laravel中执行子查询,因为它们将在运行第一个查询以附加关系后执行。将其替换为take(1),将解决您的N + 1问题。