首页 > 解决方案 > 如何在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

标签: phplaraveleloquentrelationship

解决方案


您应该将getCategory()函数重命名为 simple category()。这使关系名称更加简单明了,并且可能解决了您的问题。

那么,你应该可以打电话了whereHas('category', ...)

如果它仍然不起作用,只需将 a 链接->toSql()到您的任何查询并以这种方式调试实际查询。


推荐阅读