簡體   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