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

Laravel多模型数据过滤:按KategoriID与MerchantID筛选

Laravel 多关联条件过滤实现方案

核心问题明确:wherePivot仅用于过滤**中间表(merchant_produk)**内的字段,而kategori_id属于produks表,因此直接用wherePivot无法实现需求,需通过关联查询完成筛选。

第一步:确认模型关联定义正确

确保各模型的关联关系配置无误:

  • Merchant 与 Produk 的多对多关联:
class Merchant extends Model
{
    public function produks()
    {
        return $this->belongsToMany(Produk::class, 'merchant_produk');
    }
}
  • Produk 与 Kategori 的一对多关联:
class Produk extends Model
{
    public function kategori()
    {
        return $this->belongsTo(Kategori::class);
    }

    // 反向关联(可选,用于方法二)
    public function merchants()
    {
        return $this->belongsToMany(Merchant::class, 'merchant_produk');
    }
}

方法一:通过商家模型关联筛选

在控制器的selectedmerchant方法中,先定位目标商家,再筛选其关联商品中属于指定分类的记录:

public function selectedmerchant($merchantId, $kategoriId)
{
    $merchant = Merchant::with(['produks' => function ($query) use ($kategoriId) {
        // 筛选商品所属分类ID匹配的记录
        $query->whereHas('kategori', fn($subQuery) => $subQuery->where('id', $kategoriId));
    }])->findOrFail($merchantId);

    return $merchant->produks;
}

方法二:直接从商品模型发起查询

如果仅需要返回符合条件的商品集合,可直接从Produk模型入手,同时匹配商家ID和分类ID:

public function selectedmerchant($merchantId, $kategoriId)
{
    return Produk::where('kategori_id', $kategoriId)
        ->whereHas('merchants', fn($query) => $query->where('merchant_id', $merchantId))
        ->get();
}

关键说明

  • wherePivot的适用场景:仅当需要过滤中间表(如merchant_produk)中的自定义字段(例如is_active)时才使用,比如$query->wherePivot('is_active', 1)。
  • 两种方法均可实现需求,可根据实际返回数据的格式(是否需要包含商家信息)选择对应方案。

内容的提问来源于stack exchange,提问作者Mohammad Farid Hasymi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:37:02