简体   繁体   English

Laravel帖子和标签:有很多直通关系吗?

[英]Laravel posts and tags: has many through relationship?

I'm making a Laravel application. 我正在制作Laravel应用程序。

I have a posts table that stores "blog posts". 我有一个帖子表,用于存储“博客帖子”。 I also have a tags table to store tags (eg: "Cooking" for cooking posts, "Books" for book posts). 我也有一个标签表来存储标签(例如:“ Cooking”用于烹饪帖子,“ Books”用于书籍帖子)。 Each post can have many tags. 每个帖子可以有很多标签。 I setup my database as such 我这样设置数据库

Posts 帖子

  • id ID
  • text 文本
  • title 标题

Tags 标签

  • id ID
  • name 名称

PostTags PostTags

  • id ID
  • tag_id TAG_ID
  • post_id POST_ID

Is this a "HasManyThrough" relationship in Laravel/Eloquent? 这是Laravel / Eloquent中的“ HasManyThrough”关系吗? I tried setting up my model using 我尝试使用建立模型

public function tags()
{
   return $this->hasManyThrough('App\Tag', 'App\PostTag')
}

However, this isn't working - throwing exceptions telling me the column names don't exist. 但是,这行不通-抛出异常告诉我列名不存在。

This was actually a "belongsToMany" relationship - what I was missing was the fact you can specify a pivot table using an argument when declaring the relationship like so: 这实际上是一个“ belongsToMany”关系-我所缺少的是您可以在声明关系时使用参数来指定数据透视表,如下所示:

public function tags()
{
   return $this->belongsToMany('App\Tag', 'post_tags')
}

It is not a has-many-through relationship. 这不是“多对多”的关系。

A post can belong to many tags (eg: post "Foobar" can belong to "foo" and "bar" tags). 一个帖子可以属于许多标签(例如:帖子“ Foobar”可以属于“ foo”和“ bar”标签)。 A tag can belong to many posts (eg: tag "foo" can belong to posts "Foobar" and "Another post"). 标签可以属于许多帖子(例如:标签“ foo”可以属于帖子“ Foobar”和“另一个帖子”)。

So, in a Post class you would have 因此,在Post课程中

public function tags()
{
    return $this->belongsToMany(Tag::class);
}

and in the Tag class you would define the inverse 然后在Tag类中定义反函数

public function posts()
{
    return $this->belongsToMany(Post::class);
}

Read more in the official docs . 官方文档中了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM