laravel 过滤不起作用的雄辩关系

iszxjhcz  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(137)

我有一个表cities和一个与headquarters表的关系,这是City.php中的关系。

public function headquarters() {
  return $this->hasMany('App\Headquarter'); 
}

在我的控制器中,我试图找到那些有实体总部的城市。

$city_headquarters = City::whereHas('headquarters', function($query) {
   $query->where('headquarter_type', 'physical');         
})->get();

我没有得到任何错误,但如果至少有一个物理总部,我甚至得到那些headquarter_type不是物理的。
查询是否正确,或者我怎么才能只得到物理总部?

xzv2uavs

xzv2uavs1#

您的查询是获取至少有一个总部(headquarter_type设置为physical)的所有城市
如果你只想有城市只有物理总部,那么你应该使用这个:

$city_headquarters = City::whereDoesntHave('headquarters', function($query){
   $query->where('headquarter_type', '<>', 'physical');  
})->get();

如果只想立即加载物理总部,则:

$city_headquarters = City::whereHas('headquarters', function($query) {
   $query->where('headquarter_type','physical');
})->with([
    'headquarters' => function($query) {
          $query->where('headquarter_type', 'physical');
    }
])->get();

然后您可以:

foreach($city_headquarters as $city) {
   foreach($city->headquarters as $physical_headquarter) {
      $physical_headquarter->[...]
   }
}

相关问题