如何在Eloquent中使用whereHas获取关联多态表的数据?
在Eloquent中通过whereHas从多态关联表获取数据
你的代码方向是正确的,只需确保多态关联配置无误,并注意查询的细节:
1. 校验多态关联定义
首先确认House模型里的extendable多态关联定义正确:
// House 模型 public function extendable() { return $this->morphTo(); }
关联目标模型(如Project)也需要配置反向关联:
// Project 模型 public function houses() { return $this->morphMany(House::class, 'extendable'); }
2. 完善查询代码
你的现有查询逻辑没问题,但要返回实际的数据集,记得添加get()方法。如果需要限定关联的模型类型,可额外添加条件:
return House::whereHas('extendable', function($query) use($projectdeciphered){ $query->where('project_id', $projectdeciphered) // 可选:强制关联类型为Project模型,避免匹配其他多态模型 ->where('extendable_type', Project::class); })->get();
3. 拓展场景用法
- 同时筛选多种多态关联类型:
return House::whereHas('extendable', function($query) use($targetIds){ $query->whereIn('id', $targetIds) ->whereIn('extendable_type', [Project::class, OtherRelatedModel::class]); })->get();
- 预加载关联模型,避免N+1查询:
return House::with('extendable') ->whereHas('extendable', function($query) use($projectdeciphered){ $query->where('project_id', $projectdeciphered); })->get();
内容的提问来源于stack exchange,提问作者Deogratias Alison
相关产品推荐
相关产品推荐

