laravel - 多类别嵌套查询 Laravel 5

标签 laravel laravel-5 eloquent

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

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

这就是我现在所拥有的:

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

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

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

谢谢。

最佳答案

如果您只有一层子类别,我将使用以下解决方案。

<?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);

关于laravel - 多类别嵌套查询 Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224301/

相关文章:

php - 拉拉维尔。两个项目的公共(public)队列

php - 如何将带有变量的 where 条件添加到我的 Controller ?

javascript - 数据作为对象和数组传递?

php - Laravel 文件管理器动态 base_directory

php - 拉拉维尔 5 : removing a record from a pivot table with routing issue - NotFoundHttpException

javascript - 如何将 Eloquent 模型传递给 Knockout.js View 模型构造函数?

php - 与 Laravel 和 Eloquent 的三向关系

php - Laravel AES-256加密和MySQL

php - 如何在 Laravel 中获取 Action 名称?

laravel - 如何使用 Eloquent 在 Laravel 中开始查询?