mysql - 如何使用 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
解决方案
为 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)
推荐阅读
- javascript - Vue - 安装后访问子组件默认道具
- python - 如何将图像的轮廓保存为另一张图像?
- python - 如何创建使用 pybind 创建的 python 包?
- react-native - 如何使用酶玩笑在本机反应中编写导航堆栈的单元测试用例?
- python - 使用 Django-q 的 Django 计划任务
- google-sheets - 谷歌电子表格 - If() SUM
- mysql - 如何使用 Vitess 增加分片
- mongodb - 如何让 MongoDB $map 运算符返回值数组而不是任何对象数组?
- wpf - 如何在 Windows 中创建后台进程应用程序?
- angular - 基于条件的动态验证