使用Zend Framework 2和tableGateway的COUNT和GROUP BY

Tom*_*Tom 7 zend-framework2

在Zend Framework 2中,使用tableGateway,我想运行以下SQL查询:

  SELECT categories.category_name, COUNT(forums.forum_id)
    FROM categories LEFT JOIN forums
      ON categories.category_id = forums.category_id
GROUP BY categories.category_name;
Run Code Online (Sandbox Code Playgroud)

问题是我根本不知道该怎么做.我知道如何使用$select->join()例如,但我无法弄清楚如何做一个COUNTGROUP BY.

我想要的SQL:我有2个表; categoriesforums.我想从categories我想要论坛数量的每个类别中选择所有类别.

Tom*_*Tom 14

另一个论坛上有人给了我正确答案,这对我有用.以为我会分享它,以防其他人有类似的问题.我现在就是这样的:

use Zend\Db\Sql\Expression;

$resultSet = $this->tableGateway->select(function (Select $select)
{
    // Select columns and count the forums.
    $select->columns(array(
        'category_name',
        'forumsCount' => new Expression('COUNT(forums.forum_id)')
    ));

    // Left-join with the forums table.
    $select->join('forums', 'categories.category_id = forums.category_id', array(), 'left');

    // Group by the category name.
    $select->group('categories.category_name');
});

return $resultSet;
Run Code Online (Sandbox Code Playgroud)