Laravel 5 我应该如何使用HasManyThrough通过Laravel中的2个数据透视表连接3个表?

Laravel 5 我应该如何使用HasManyThrough通过Laravel中的2个数据透视表连接3个表?,laravel-5,eloquent,Laravel 5,Eloquent,我很难理解Laravel 5.8中的HasManyThrough关系,我认为这是我需要使用的,但我不知道如何实现。我试着跟随一段Laracasts视频,Jeffrey在视频中描述了这段视频并阅读了文档,但我似乎无法理解这个概念,现在感觉自己相当愚蠢 如何在模型中定义关系,并在ProductsController中编写正确的雄辩查询,以便在共享相同标记id的产品视图中显示帖子 例如,我有一篇贴有“mbti”标签的帖子,还有一个产品也贴有“mbti”标签。我将如何在相关产品视图中显示这些相关帖子?到

我很难理解Laravel 5.8中的HasManyThrough关系,我认为这是我需要使用的,但我不知道如何实现。我试着跟随一段Laracasts视频,Jeffrey在视频中描述了这段视频并阅读了文档,但我似乎无法理解这个概念,现在感觉自己相当愚蠢

如何在模型中定义关系,并在ProductsController中编写正确的雄辩查询,以便在共享相同标记id的产品视图中显示帖子

例如,我有一篇贴有“mbti”标签的帖子,还有一个产品也贴有“mbti”标签。我将如何在相关产品视图中显示这些相关帖子?到目前为止,我已经设法在视图中显示标记,但我希望与该标记关联的帖子也能显示出来。我很感激任何关于我应该如何处理这个问题的指导

我有3个表和2个数据透视表(为了简洁起见删除了一些列名):

我的型号:

Post.php

public function tags() {
   return $this->belongsToMany('App\Tag')->withPivot('tag_id');
}
Tag.php

public function posts() 
{
  return $this->belongsToMany('App\Post')->withPivot('post_tag');
}

public function products() 
{
  return $this->belongsToMany('App\Product')->withPivot('product_tag');
}
Product.php

public function tags() 
{
  return $this->belongsToMany('App\Tag')->withPivot('product_id');
}

最后,我在我的
products
表中添加了一个
tag\u id
列,并在那里引用了标签id。我的应用程序中的一个产品只能分配一个标记,因此对数据透视表的需求是多余的,增加了不必要的复杂性

在我的
Tag.php
模型中,我将关系定义为:

public function products() 
{
    return $this->hasManyThrough('App\Post', 'App\Product');
}

在我的
ProductsController.php
中,我选择了显示方法中的标记:

$tag = Tag::where('id', '=', $product->tag_id)->first();
if($tag) {
 $tags = Tag::whereName($tag->name)->first();
}
$tag = Tag::where('id', '=', $product->tag_id)->first();
if($tag) {
 $tags = Tag::whereName($tag->name)->first();
}