我想按帖子数量获得前5名,例如:
Cat 1 = 10 posts
Cat 2 = 7 posts
Cat 3 = 5 posts
Cat 4 = 3 posts
Cat 5 = 2 posts
我知道我可以通过急切的加载和他们的帖子获得我的类别 计算每个类别的帖子数量,但这不给我
asc
按类别排序,因此我正在考虑加入查询。
这是我到目前为止所做的,并且遇到了这个问题
我收到此错误
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'publish' in where clause is ambiguous (SQL: select * from
个类别inner join
帖子on
帖子.
类别=
类别.
id where
发布= 1 limit 5)
$categoriesbyposts = Category::where('publish', '=', 1)
->join('posts', 'posts.categories', '=', 'categories.id')
// ->where('posts.publish', '=', 1)
->take(5)
->get();
PS:我可能需要提到的是,我的帖子表中没有category_id
列,我正在使用名为post_categories
的第三张表,它得到了{{1 }}和post_id
。
有什么主意吗?
category_id
post model
public function categories(){
return $this->belongsToMany(Category::class, 'post_categories', 'post_id', 'category_id');
}
category model
我最终得到下面的代码,它返回5个帖子,而不是5个类别!
public function posts(){
return $this->belongsToMany(Post::class, 'post_categories');
}
答案 0 :(得分:1)
尝试一下,让我知道结果如何
IMFActivate
另一种选择是
$results = DB::select('
SELECT c.category_name, c.slug, COUNT(pc.post_id) AS `post_count`
FROM categories AS c JOIN post_categories AS pc
ON c.id = pc.category_id
JOIN posts AS p
ON posts.id = post_categories.post_id
WHERE c.publish = 1 AND p.publish = 1
GROUP BY category_name
ORDER BY post_count DESC
LIMIT 5
');
答案 1 :(得分:0)
请在哪个表适用此条件的位置添加表名
从posts.categories = categories.id的类别内部联接帖子中选择*,其中category.publish = 1个限制5)