【问题标题】:How to display blog post's multiple tags in blog post's blade template using laravel?如何使用 laravel 在博客文章的刀片模板中显示博客文章的多个标签?
【发布时间】:2019-08-06 02:39:27
【问题描述】:

我有两个表:tagsblog_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

【问题讨论】:

  • 为什么要存储以逗号分隔的标签?您不能将每个存储在单独的字段中吗?
  • 因为标签列表很长。一篇文章可能包含超过 50 个标签。
  • 好的,但你也可以使用数据透视表。

标签: mysql laravel laravel-5 query-builder


【解决方案1】:

我想建议使用一对多或多对多。但是 你可以这样试试

在您的帖子模型中

 class Post extends Model
    {
        public function getTag(){
            $s = array();
            $post_tags =  explode(',',str_replace(array('[',']'),'',$this->post_tags));
            foreach ($post_tags as &$value) {
                array_push($s,$value);
            }
            $tags = Tag::whereIn('id',$s)->get()->pluck('tag_name');

            return implode(",",$tags->toArray());
        }
    }

在你的刀片内部

<ul>
  @foreach($posts as $post)
    <li>
        {{$post->getTag()}}
    </li>
  @endforeach
</ul>

或者

<ul>

        @foreach($posts as $post)
            <li>
                @php
                    $s = array();
                      $post_tags =  explode(',',str_replace(array('[',']'),'',$post->post_tags));
                      foreach ($post_tags as &$value) {
                          array_push($s,$value);
                      }
                      $tags = App\Tag::whereIn('id',$s)->get()->pluck('tag_name');

                      $tags =implode(",",$tags->toArray());
                @endphp
                {{$tags}}

            </li>
        @endforeach
    </ul>

【讨论】:

    【解决方案2】:

    为 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多