繁体   English   中英

按他们在laravel中的帖子获取类别顺序

[英]Get categories order by their posts in laravel

我想按其帖子数获得前5个类别,例如:

Cat 1 = 10 posts
Cat 2 = 7 posts
Cat 3 = 5 posts
Cat 4 = 3 posts
Cat 5 = 2 posts

我知道我可以通过急切的加载获取我的类别及其帖子,并计算每个类别的帖子数量,但这并不能给我按类别的asc排列,因此我正在考虑加入查询。

这是我到目前为止所做的,并且存在此问题

  1. 我无法放置帖子的状态(仅获取具有已发布状态的帖子并仅对其进行计数)
  2. 我得到这个错误

    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第三张表,它获取了post_idcategory_id

任何想法?

更新

post model

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

category model

public function posts(){
        return $this->belongsToMany(Post::class, 'post_categories');
    }

更新2

我最终得到下面的代码,它返回5个帖子,而不是5个类别!

$categoriesbyposts = DB::table('categories')
            ->where('categories.publish', '=', 1)
            ->join('post_categories', 'post_categories.category_id', '=', 'categories.id')
            ->join('posts', 'posts.id', '=', 'post_categories.post_id')
            ->groupby('categories.id')
            ->take(5)
            ->get();

试试这个,让我知道结果如何

$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
');

另一种选择是

$results = Category::selectRaw('categories.category_name, categories.slug,  COUNT(post_categories.post_id) AS `post_count`')
            ->join('post_categories', 'categories.id', '=', 'post_categories.category_id')
            ->join('posts', 'posts.id', '=', 'post_categories.post_id')
            ->whereRaw('categories.publish = 1 AND posts.publish = 1')
            ->groupBy('category_name')
            ->orderBy('post_count', 'DESC')
            ->limit(5)
            ->get();

请在哪个条件适用此条件的地方添加表名称

从posts.categories = categories.id上的类别内部联接帖子中选择*,其中category.publish = 1个限制5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM