Laravel Eloquent 的 ->load() 回调不影响结果集

Laravel Eloquent's ->load() With Callback Not Affecting Resultset

我想获取一个父对象(在本例中为 Person)并在其上加载一堆关系,其中许多关系具有作为回调传递给 ->load() 的自定义查询参数.例如:

public function some_method(Request $request, Person $person) {

$person->load([
   'things' => function ($query) {
      $query->where('status', 'active')
         ->whereDate('created_at', '<', '2021-01-01');
   },
   'other_things' => function ($query) {
      $query->where('status', 'active')
         ->where('color', 'red');
   },
   ... Many more callback-based relationships ...
]);

当我使用 return view('...', compact('person')) 将其传递给 Blade 模板并开始循环某些关系时,如下所示:

@foreach ($person->things as $thing)
{{ $thing->status == 'active' ? 'Active' : 'Inactive' }}
@endforeach

我得到许多 Thing 不活动的并且不符合控制器中 ->load() 函数的 ->whereDate() 查询。我希望 load([...]) 中的自定义回调来过滤结果关系,但是当访问 Blade 模板中的关系时,似乎执行了查询,就好像没有回调函数一样。

我试过使用 with(),但考虑到我在 URI 中注入 Person,这似乎不是处理它的正确方法。我也尝试过将 ->map() 与各种循环结构一起使用,但这些循环结构也会被似乎是对数据库的第二轮 Eloquent 调用覆盖。

我需要做什么才能让 Blade 模板“尊重”我希望用来过滤加载到父对象上的记录的自定义回调查询?

谢谢!

您可以尝试一些方法。

选项 1

这应该不是必需的,但您可以尝试用加载的结果覆盖 $person

$person = $person->load();

选项 2

截至 Laravel 8.43 you can use Model::preventLazyLoading(! app()->isProduction()); in the boot method of app/Providers/AppServiceProvider.php. This will prevent any lazy loading , also in views. If there is lazy loading it will return an error. image source