首页 > 解决方案 > 如何使用 laravel 在博客文章的刀片模板中显示博客文章的多个标签?

问题描述

我有两个表:标签blog_post 每个帖子都有多个标签存储在单列中(用逗号分隔)。

标签表:

  tag_id   tag_name
    1       Health
    2       Beauty
    3       Fitness
    4       Yoga

Blog_post 表

  post_id   post_tags
    1         1,2
    2         2,3,4
    3         1,4

我需要使用 laravel 中的 Query builder 根据 post_id 获取标签名称。比如:如果 post_id = 1

Health,Beauty 

如果 post_id = 2

Beauty, Fitness, Yoga

标签: mysqllaravellaravel-5query-builder

解决方案


为 post_tag 表制作数据透视表并将 post_id 和 tag_id 存储在该表模式中

 post_tag
  -id
  -post_id
  -tag_id

并使用附加或同步方法,您可以将多个标签附加到一篇文章。

比您可以使用多对多关系检索数据。

在 Post Model 中为标签建立关系

  public function tags()
  {
     return $this->belongsToMany('App\Tag', 'post_tag', 'post_id', 'tag_id');
  }

比检索标签

$productTags = Product::with('tags')->find(1)

推荐阅读