使用 NotORM 获取 PHP 中文章的总评论


Get total comments of article in PHP with NotORM

我的注释表看起来像:

| ID | article_id | user_id | ...
|-------------------------------|
|  1 |      1     |    1    | ...
|  2 |      2     |    2    | ...
|  3 |      2     |    1    | ...
|  4 |      3     |    2    | ...

而且我需要获得评论最多的前 5 篇文章。当我在 SQL 控制台 SELECT 'article_id', count(*) as 'total' FROM 'comments' GROUP BY 'article_id' ORDER BY 'total' LIMIT 5 中使用此语句时,我得到了我想要的一切。但我需要使用 NotORM 来做到这一点,这就是我坚持的地方。这是我获取这些文章的功能:

function getBestActive() {
    $items = $this->db->comments()
                ->select("article_id, count(*) as 'total'")
                ->order("total DESC")
                ->limit(5);
    $articles = array();
    foreach($items as $item) {
        $article = $this->db->article('id', $item['article_id'])->fetch();
        $article['img'] = "thumb/{$article['uri']}.jpg";
        $article['comments'] = $item['total'];
        $articles[] = $article;
    }
    return $articles;
}

但它返回的数组只有 1 篇文章(评论最多),我需要最多的 5 篇文章。或者是否可以使用 NotORM 执行自定义 SQL 语句(这也可能是答案)?

哦,

现在我明白了。我忘了添加group()功能。因此,使用此选择一切正常:

$items = $this->db->comments()
            ->select("article_id, count(*) as 'total'")
            ->group("article_id")
            ->order("total DESC")
            ->limit(5);