You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel多态关联场景下如何正确使用whereRelation?

问题原因

虽然你已经在主表过滤了model_type = Partner::class,但Laravel的whereRelation处理多态关联(morphTo类型的model关联)时,会默认考虑所有可能关联的模型表,导致SQL查询中混入了没有category_id字段的表,最终触发报错。

可行解决方案

方案1:用whereHas+whereInstanceOf(Laravel 9+推荐)

通过whereInstanceOf直接限定多态关联的模型类型,确保只关联Partner表,再过滤分类ID:

$this->contacts = Person::whereHas('model', function ($query) {
    // 强制关联的是Partner模型
    $query->whereInstanceOf(Partner::class);
    
    // 选中分类时过滤category_id
    if ($this->selected_category) {
        $query->where('category_id', $this->selected_category);
    }
})->get();

方案2:直接关联Partner表(兼容全版本)

既然明确只查关联Partner的Person,可以手动JOINPartner表,避开多态关联的动态表问题:

$this->contacts = Person::where('model_type', Partner::class)
    ->when($this->selected_category, function ($query) {
        $query->join('partners', 'persons.model_id', '=', 'partners.id')
              ->where('partners.category_id', $this->selected_category)
              ->select('persons.*'); // 指定查询Person表字段,避免表字段冲突
    })
    ->get();

方案3:定义专属多态关联

在Person模型里新增一个仅关联Partner的多态关联方法:

// Person模型中
public function partner()
{
    return $this->morphOne(Partner::class, 'model');
}

然后使用这个专属关联做whereRelation查询:

$this->contacts = Person::where('model_type', Partner::class)
    ->when($this->selected_category, function ($query) {
        $query->whereRelation('partner', 'category_id', $this->selected_category);
    })
    ->get();

内容的提问来源于stack exchange,提问作者Awayn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 15:45:26