Laravel Eloquent 在 whereHas() 上制作 select

Laravel Eloquent making select on whereHas()

我怎样才能 select 在 whereHas() 相关的某些列上。

我当前的查询如下所示

Location::select(['title'])
->withCount(['job' => function($q) {
          return $q->where('language_id', 1)->whereNull('deleted_at');
        }])->whereHas('country', function ($q) {
            return $q->where('id', '=', 80);
        })->get();

我试过了

Location::select(['title', 'id as value'])->withCount(['job' => function($q) {
          return $q->where('language_id', 1)->whereNull('deleted_at');
        }])->whereHas('country', function ($q) {
            return $q->select('title', 'iso3')->where('id', '=', 80);
        })->get();

但是 country 关系没有任何返回。我如何重构此查询以使其正常工作?

whereHas() 不急于加载关系,只根据它过滤结果。要预先加载,请使用 with().

Location::with('country:id,title,iso3')
    ->select(['title', 'id as value', 'country_id'])
    ->withCount(['job' => function($q) {
        $q->where('language_id', 1)->whereNull('deleted_at');
    }])
    ->whereHas('country', function ($q) {
        $q->where('id', '=', 80);
    })->get();