laravel 如何使用多个约束进行预加载?

How to do laravel eager loading with multiple constraints?

$institutes = Institute::with(['address' => function($query){
                 $query->whereCityId(Input::get('city_id'));
                 $query->whereIn('area_id',Input::get('area_id'));
              }])->get();

为 foreach() 提供的参数无效

问题可能出在这里

$query->whereIn('area_id',Input::get('area_id'));

尝试确保 Input::get('area_id') 实际上是 returns 一个数组:

$area = Input::get('area_id') ?: [];
$query->whereIn('area_id',is_string($area) ? json_decode($area, true) : $area);

whereCityId 是模型的范围吗?文档中包含范围仅与模型链接的示例。

尝试用列名替换范围并尝试。 ex 替换为 city_id

 $institutes = Institute::with(['address' => function($query){
                     $query->where('city_id',Input::get('city_id'));
                     $query->whereIn('area_id',Input::get('area_id'));
                  }])->get();

它确实有效,但它 returns

address: null

条件匹配的地方。但是它returns所有研究所。我们可以在集合上使用 filter 或者 whereHas

$institutes = Institute::whereHas('address', function ($query) use ($city_id) {
                   $query->whereCityId($city_id);
              })->get();

$institutes = Institute::with(['address' => function ($query) use ($city_id) {
                   $query->whereCityId($city_id);
              }])->get()->filter(function ($institute){ 
                   return $institute->address != null; 
              });