Laravel:为什么急于加载只会保​​留上一个模型的结果?

时间:2018-09-27 18:22:19

标签: laravel laravel-5 eloquent laravel-5.1 eager-loading

如果我执行以下操作:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9])
                    ->get();

然后我得到以下结果:

Illuminate\Database\Eloquent\Collection {#1104
 all: [
   App\Assignment {#1112
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#986
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#945
         all: [
           App\Record {#853
             id: 6624,
             unit_id: 6,
             process_date: "2017-09-19",
             process_hour: 14,
           },
         ],
       },
     },
   },
 ],
}

请注意,已加载的单位如何具有与查询匹配的记录。

现在,如果我使用完全相同的查询,但是将另一个赋值(49)添加到我的whereIn数组中:

App\Assignment::with(['unit.records' => function ($q) {
                    $q->where('process_date', '>=', '2016-01-01')
                        ->where('process_date', '<=', '2018-09-27')
                        ->orderBy('process_date')
                        ->orderBy('process_hour')
                        ->limit(1);
                    }])
                    ->whereIn('id', [9,49])
                    ->get();

显示了作业49的记录,但作业9的记录不再显示:

Illuminate\Database\Eloquent\Collection {#1032
 all: [
   App\Assignment {#1014
     id: 9,
     unit_id: 6,
     start_date: "2015-11-25",
     end_date: "2016-01-04",
     unit: App\Unit {#1283
       id: 6,
       records: Illuminate\Database\Eloquent\Collection {#1254
         all: [],
       },
     },
   },
   App\Assignment {#1061
     id: 49,
     unit_id: 29,
     start_date: "2017-02-24",
     end_date: "9999-12-31",
     unit: App\Unit {#1279
       id: 29,
       records: Illuminate\Database\Eloquent\Collection {#1131
         all: [
           App\Record {#1284
             id: 6062,
             unit_id: 29,
             process_date: "2017-03-10",
             process_hour: 13,
           },
         ],
       },
     },
   },
 ],
}

与分配9的条件匹配的记录显然存在,但是由于某种原因,当查询找到多个具有与该条件的单元/记录的分配的记录时,不会加载该记录。

我也用更多分配进行了测试,在每种情况下,记录只会显示数组中的最后一个分配。

这是怎么回事?

2 个答案:

答案 0 :(得分:3)

问题是您使用的是

->limit(1)

这会将关系记录数限制为1。只需删除此行,就可以了。

答案 1 :(得分:1)

Laravel中没有对带有限制的紧急加载的本地支持。

我为此创建了一个包:https://github.com/staudenmeir/eloquent-eager-limit

在父模型和相关模型中都使用HasEagerLimit特性。

class Unit extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Record extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

然后,您可以将->limit(1)应用于您的恋爱关系,您会得到预期的结果。