我在 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/