【问题标题】:How to filter post by category in laravel?如何在laravel中按类别过滤帖子?
【发布时间】:2021-10-26 16:35:50
【问题描述】:

我目前正在尝试在 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

【问题讨论】:

  • 欢迎来到 StackOverflow!当你在关系区使用whereHas或任何其他方法时,第一个参数是指你的模型的方法(getCategory),而不是表。看看@Flame 的回答。这就是建议。

标签: php laravel eloquent relationship


【解决方案1】:

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

那么,您应该可以拨打whereHas('category', ...)

如果仍然无法正常工作,只需将->toSql() 链接到您的任何查询并以这种方式调试实际查询。

【讨论】:

  • 我使用和错误(1/1) ErrorException. compact(): Undefined variable: operator
  • @sawyer 我不知道这是从哪里来的。该错误应该指出您要查看的确切位置。
  • 它成功了 Jessé kalil Martins Da Silva,谢谢$post_category = DB::table('post_category')->where('category_id', ?)->get(); $post = DB::table('post')->whereIn('id', $post_category->pluck('post_id'))->get();
【解决方案2】:

显然一切都很好!

一个建议是在belongsToMany 方法中再添加两个参数,例如:

public function getCategory()
{
    return $this->belongsToMany(Category::class, 'post_category', 'post_id', 'category_id');
}

https://laravel.com/api/7.x/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_belongsToMany

【讨论】:

  • 我尝试了,但它不起作用。 (1/1) ErrorException compact(): Undefined variable: operator我用的是laravel 5.4
  • 它可能是版本 5.4 issue 也许解决方案是使用类似:DB::select ('select * from post p where id in (select (post_id) from post_category ua where category_id = ?)');$post_category = DB::table('post_category')->where('category_id', ?)->get(); $post = DB::table('post')->whereIn('id', $post_category->pluck('post_id'))->get();
  • 是的!我用了你的方法。有用。谢谢
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2017-06-12
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多