【问题标题】:Laravel Eloquent making select on whereHas()Laravel Eloquent 在 whereHas() 上进行选择
【发布时间】:2021-03-26 10:17:59
【问题描述】:

如何在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 关系上没有返回任何内容。如何重构此查询以使其正常工作?

【问题讨论】:

    标签: laravel select eloquent orm relationship


    【解决方案1】:

    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();
    

    【讨论】:

    • 感谢您的反馈,如果我删除选择而不是得到我要求的字段,但不知何故,在主表上选择将返回 null 作为结果。
    • 您必须确保从主表locations 中选择所需的外键,否则可能无法匹配相关模型
    • 我删除了别名但结果还是一样
    • 您需要在选择中包含将位置记录排列到国家记录的外键。我猜这个别名是错误的。例如,如果 country_id 是位置表上的外键,将其链接到国家表上的记录 - 在选择中包含 country_id
    猜你喜欢
    • 2020-04-22
    • 2021-08-23
    • 1970-01-01
    • 2019-12-28
    • 2017-06-09
    • 2020-09-16
    • 2018-10-20
    • 2014-09-30
    • 2020-12-23
    相关资源
    最近更新 更多