Search code examples
phpmysqlzend-framework2zend-db

how to write count query with left join in zend frame work2?


Hi I am new to Zend Framework. In normal php I know how to write queries. But in Zend Framework this is totally different.

I have written the query with left join and it is working fine but the thing is I want to get count of the joined table id. I will show my controller code:

controller:

$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$projectTable = new TableGateway('blog', $adapter);
$rowset = $projectTable->select(
    function(Select $select) {       
        $select->join(
            array('b' => 'blog_answers'),
            "b.question_id = blog.id",
            array('new'=>COUNT('b.question_id'),'left')
        ); 
    }
);

while running this i am getting can you please clarify this how get the count.


Solution

  • HI this is the correct Query i got.

    `
    $adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
            $projectTable = new TableGateway('blog', $adapter);
            $rowset = $projectTable->select(function(Select $select) {
           $select->columns(array(
            '*',
            'num' => new Expression('COUNT(blog_answers.question_id)')
        ));
            $select->join('blog_answers', 'blog.id = blog_answers.question_id', array(), 'left');
             $select->group('blog.id');     
                });`