php - 如何在laravel中按类别过滤帖子?
问题描述
我目前正在尝试在 3 个表之间建立关系。
post
id
name
category
id
name
post_category
id
post_id
category_id
数据库
邮政 | 1 | 帖子1 | | 2 | 帖子2 | | 3 | 帖子3 | 类别 | 1 | 猫1 | | 2 | 猫2 | | 3 | 三类 | post_category | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 3 | 2 | | 3 | 2 | 2 | | 3 | 1 | 3 |模型 Post.php
公共函数 getCategory() { 返回 $this->belongsToMany(Category::class, 'post_category'); }PostController.php
$data = Post::with('getCategory')->get();它返回正确的帖子列表。
现在我想按类别过滤帖子。我尝试,但它不起作用
$categoryId = [1,2]; $data = Post::with('getCategory')->whereHas('category', function ($query) use ($categoryId) { $query->whereIn('id', $categoryId); })->orderBy('id','DESC')->get();请帮我使用 Laravel 5.4
解决方案
您应该将getCategory()
函数重命名为 simple category()
。这使关系名称更加简单明了,并且可能解决了您的问题。
那么,你应该可以打电话了whereHas('category', ...)
。
如果它仍然不起作用,只需将 a 链接->toSql()
到您的任何查询并以这种方式调试实际查询。
推荐阅读
- reactjs - 使用酶异步安装后测试反应子组件
- c# - WOPI主机中的UnlockAndRelock方法
- json - 我们可以传递 JSON 格式来阅读文档吗?
- html - 为什么我的 html 元素在使用媒体查询时重复和重叠?
- javascript - 是否可以将全日历的布局从 00:00:00 - 23:59:00 更改为 19:00:00 - 06:59:00?
- python - Django 无法使用有效凭据登录
- python-3.x - 如何修复烧瓶上双路由的 Flask-Bootstrap4 内部服务器错误
- .net - 在.net core 项目中添加.net framework 类库引用会出现什么问题?
- java - 在 Akka Clustering 的情况下如何存储传入的请求?
- automation - DFA的状态图