【问题标题】:Multiple Category Nested Query Laravel 5多类别嵌套查询 Laravel 5
【发布时间】:2015-10-19 21:33:18
【问题描述】:

我在 Laravel 5 上为多级类别系统遵循了这个代码结构:

这很好用。但我正在尝试组合一个查询来返回一个类别中的帖子(按 slug)以及下面的子类别。

这就是我目前所拥有的:

    $posts = Post::with('images')->whereHas('categories', function($q) use ($slug)
    {
        $q->where('slug', '=', $slug);

    })->orderBy('created_at', 'DESC')->paginate(10);

这将返回与通过的 slug 匹配的类别下的所有内容,但不返回子项。有什么建议吗?

谢谢。

【问题讨论】:

  • 能不能有一个子类的子类?

标签: laravel laravel-5 eloquent


【解决方案1】:

如果您只有一个深度的子类别,我会使用以下解决方案。

<?php
$category = Category::where('slug',$slug)->first();
$posts = Post::with('images')->whereHas('categories', function($q) use ($category)
{
    $q->where(function($q) use ($category) {
      $q->where('id', $category->id)->orWhere('parent_id',$category->id);
    });
})->orderBy('created_at', 'DESC')->paginate(10);

【讨论】:

  • 我认为这很接近,逻辑似乎是正确的,但它似乎正在返回所有帖子。这是生成的查询:select * from 'posts' where 'posts'.'deleted_at' is null and (select count(*) from 'categories' inner join 'category_post' on 'categories'.'id' = 'category_post'.'category_id' where 'category_post'.'post_id' = 'posts'.'id' and 'id' = '9' or 'parent_id' = '9' and 'categories'.'deleted_at' is null) &gt;= 1 order by 'created_at' desc limit 10 offset 0 - 但是我认为 id 和 parent_id 周围需要有括号......所以(id = '9' 或 parent_id = '9')。有什么想法吗?
  • 由于它使用的是连接,因此它会稍微混淆查询。我编辑了答案以正确分组条件,以避免与 OR 运算符进行未分组比较。
【解决方案2】:

在您的代码中,您只获取了Posts 和它们的images。如果我理解正确,您要获取的是Posts、imagescategory 他们的输入和childCategories(这是一个编造的名称)category。您只需在您的 with 方法中添加 category.childCategories,如下所示:

$posts = Post::with('images', 'categories.childCategories')->whereHas('categories', function($q) use ($slug)
{
    $q->where('slug', '=', $slug);

})->orderBy('created_at', 'DESC')->paginate(10);

记住将childCategories 名称更改为Category 模型中的任何子类别关系名称。

【讨论】:

  • 您好,我想从类别和子类别中检索帖子。因此,来自 dboskovic 的概念是,该解决方案目前返回所有帖子。
猜你喜欢
  • 2018-09-10
  • 1970-01-01
  • 2016-05-17
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
相关资源
最近更新 更多