如何在Zend \ Db \ Sql中使用聚合函数?

时间:2013-11-08 09:11:10

标签: php sql zend-framework2

以下代码给出错误类Zend \ Db \ Sql \ Expression的对象无法转换为字符串;

$select->join(array('tt' => 'discuss_thread_tag'),
                  'tt.tag_id = discuss_tag.tag_id',
                  array(),
                  'left')
           ->join(array('t' => 'discuss_thread'),
                  't.thread_id = tt.thread_id',
                  array(new Expression('COUNT(thread_id) AS thread_count')),
                  'left')
           ->join(array('m' => 'discuss_message'),
                  'm.thread_id = t.thread_id',
                  array(new Expression('MAX(post_time) AS last_post')),
                  //'*',
                  'left')
           ->group(array('discuss_tag.name', 'discuss_tag.slug', 'discuss_tag.description'));

我做错了什么?

1 个答案:

答案 0 :(得分:3)

我没有对此进行测试,但我认为应该是这样的:

$select->join(array('tt' => 'discuss_thread_tag'),
                      'tt.tag_id = discuss_tag.tag_id',
                      array(),
                      \Zend\Db\Sql\Sql::JOIN_LEFT)
               ->join(array('t' => 'discuss_thread'),
                      't.thread_id = tt.thread_id',
                      array('thread_count' => new Expression('COUNT(thread_id)')),
                      \Zend\Db\Sql\Sql::JOIN_LEFT)
               ->join(array('m' => 'discuss_message'),
                      'm.thread_id = t.thread_id',
                      array('last_post' => new Expression('MAX(post_time)')),
                      \Zend\Db\Sql\Sql::JOIN_LEFT)
               ->group(array('discuss_tag.name', 'discuss_tag.slug', 'discuss_tag.description'));

    // Debug query
    $sql = new \Zend\Db\Sql\Sql();
    var_dump($sql->getSqlStringForSqlObject($select));