ZF2 - subqueries

php, zend-framework2

Solution

My required Query:

SELECT `comment`.`id` AS `commentId`, `comment`.`comment` AS `comment`, 
            (SELECT COUNT(comment_vote.id) AS `negativeVote` 
            FROM `comment_vote` 
            WHERE vote = -1 
            AND comment_vote.commentId = comment.id) AS `nagetiveVoteCount` 
            FROM `comment`

How I created using Zend Framework 2:

$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('comment');
$selectPost = $sql->select()
        ->from('comment_vote')
        ->columns(array('negativeVote' => new \Zend\Db\Sql\Expression('COUNT(comment_vote.id)')))
        ->where('vote = -1')
        ->where('comment_vote.commentId = comment.id');
$mainSelect->columns(
        array(
            'commentId' => 'id', 'comment',
            'nagetiveVoteCount' => new \Zend\Db\Sql\Expression('?', array($selectPost)),
        )
);

$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments);

return $resultSet->toArray();

Refrence: http://eltonminetto.net/blog/2013/03/21/subqueries-no-zend-framework-2/

Thanks for all the responses.

Problem

Subquery in Zend Framework 2 My required query: ``` SELECT `comment`.`id` AS `commentId`, `comment`.`comment` AS `comment`, (SELECT COUNT(`comment_vote`.`id`) AS `negativeVote` FROM `comment_vote` WHERE vote = -1 AND `comment_vote`.`commentId` = `comment`.`id`) AS `nagetiveVoteCount` FROM `comment` ``` Please help. Thanks, Anjith

Original source