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

如何通过products表建立categories与countries的关联关系

解决方案

当然可以通过products表建立categories与countries之间的关联关系,以下是两种可行的实现方式:

方法一:使用Laravel原生多对多关联(推荐)

由于products表同时存储了category_id和country_id外键,本质上充当了categories与countries的关联桥梁,你可以直接用belongsToMany关联来定义这种多对多关系。

在Category模型中添加如下关联方法:

use App\Models\Country;

public function countries()
{
    return $this->belongsToMany(
        Country::class,
        'products',       // 中间表名称
        'category_id',    // 当前模型在中间表的外键
        'country_id'      // 关联模型在中间表的外键
    )->distinct(); // 去重,避免同一国家因多个产品重复出现
}

使用方式:
获取指定分类下的所有国家时,直接调用关联即可:

$category = Category::find($categoryId);
$countries = $category->countries;

方法二:通过查询构造器关联查询

如果你不想定义模型关联,也可以利用现有的product与category、country的关联,通过whereHas来查询:

use App\Models\Country;

$countries = Country::whereHas('products', function ($query) use ($categoryId) {
    $query->where('category_id', $categoryId);
})->get();

补充说明

你提到的belongs-to-through扩展包同样支持这种场景,它可以更灵活地处理多层关联关系,不过上述原生方法已经能满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:55:16