COUNT and GROUP BY using Zend Framework 2 and tableGateway

后端 未结 2 1403
不思量自难忘°
不思量自难忘° 2021-01-02 16:08

In Zend Framework 2, using tableGateway, I want to run the following SQL query:

  SELECT categories.category_name, COUNT(forums.forum_id)
    FROM categories         


        
相关标签:
2条回答
  • 2021-01-02 16:45

    Someone on another forum gave me the correct answer, and this works for me. Thought I would share it in case anyone else is having a similar question. Here is how I have it now:

    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;
    
    0 讨论(0)
  • 2021-01-02 17:02

    Your query looks right. Does it work as expected when you run it directly on the database.

    I think you might just need to execute the raw query using an adapter.

    $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";
    
    $statement = $this->adapter->query($sql);
    return $statement->execute();
    
    0 讨论(0)
提交回复
热议问题