我有一张products英镑的桌子.A-product属于A-category和A-country.

我想通过依靠这段关系来找出countries A category有什么.

我考虑过hasManyThroughhttps://github.com/staudenmeir/belongs-to-through,但这是一种belongsTo的关系,两个外键都在一个中间表上,我怀疑products表的作用有点像一个透视.

我想知道如何通过products表建立一个从categoriescountries的关系--这可能吗?

表:

类别

  • ID
  • 标题

各国

  • ID
  • 标题

产品

  • ID
  • 标题
  • category_ID
  • country_ID

关系:

A product属于A country/A country有许多products.

A product属于A category/A category有许多products.

推荐答案

您已经描述了一种多对多的关系,其中Product是数据透视表.

# Category model
public function countries()
{
    return $this->belongsToMany(Country::class, 'products')
        ->withPivot(['id', 'title']); // optional
}
# Country model
public function categories()
{
    return $this->belongsToMany(Category::class, 'products')
        ->withPivot(['id', 'title']); // optional
}

Laravel相关问答推荐

Laravel将变量从模板到已发布的供应商模板

laravel错误更新使用外键的数据库

Laravel Horizo​​n 限制与优化

Laravel Valet 安装后 Ping test.dev 返回未知主机

所有 POST 请求上的 Laravel 4 CSRF

如何在laravel中将数组转换为字符串?

在 apache docker 容器中运行虚拟主机

覆盖 HTTP 标头的默认设置 (X-FRAME-OPTIONS)

我在哪里放置事件侦听器和处理程序?

Laravel 价格验证只接受正数而不是 0

Laravel 5.6 - 如何在 api 控制器中获取 auth()->user() 或 $response->user()?

如何使用 Eloquent Laravel 更新集合

Homestead 2.0 多个站点,都链接到同一个 url

Laravel 中未加密的 cookie

如何在没有 Eloquent 的情况下创建 Laravel 模型?

如何在 Laravel 查询中使用多个 OR、AND 条件

无法打开流:没有这样的文件或目录(Laravel)

测试指向外部站点的重定向链接

为什么在 Laravel 的 DB::select 中使用 DB::raw?

Laravel 检测手机/平板电脑并加载正确的视图