5

在 ZF1 中它是这样工作的:

 $selectColumns = array(
   '*',
   'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id=mytable.id").")",
 );
 $select = $db->select()->from('mytable', $selectColumns);

如何在 ZF2 中做到这一点?谢谢。

4

4 回答 4

7

请试试这个。

$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('mytable');
$subQry = $sql->select()
        ->from('orders')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(orders.id)')));
$mainSelect->columns(
        array(
            'id', 
            'orders_total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
        )
);

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

return $resultSet->toArray();

链接:ZF2 - 子查询

于 2013-04-04T09:23:18.747 回答
1

你可以试试这个:

// Make your query here using the builder if you wish, 
// but we will need to convert to string for the Expression
$sub = new Select('orders');
$sub->columns(array(new Expression('COUNT(*) as total')))
    ->where(array('id' => 4))
;
// You could just create an expression..
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");

$select = new \Zend\Db\Sql\select('tablename'); // this is inside a 

$select->columns(array('*', 'orders_total' => $subquery));

输出将是这样的:

SELECT 
    .*, 
    (SELECT COUNT(*) as total FROM "orders" WHERE "id" = '4') AS orders_total 
FROM tablename

我还没有想出一个很好的方法来使用查询生成器来执行这些类型的查询,而不必使用原始查询。

于 2012-11-22T16:44:45.983 回答
0

如果没有更多信息,您可以尝试:

 $selectColumns = array(
    '*',
    'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id", "mytable.id").")",
);
 $select = $db->select()->from('mytable', $selectColumns);

您需要在顶部添加 use 语句:

use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
于 2012-10-30T16:01:57.413 回答
0

您可以尝试将 SQL 重组为:

SELECT
    *,
    SUM(IF(O.parent_id IS NULL, 0, 1)) AS orders_total
FROM mytable
    LEFT JOIN orders O ON mytable.id = O.parent_id

您可以使用 Zend Framework 2 将其表示为:

$select = new Select('mytable');
$select->columns(array(
    '*',
    'orders_total' => new Expression("SUM(IF(O.parent_id IS NULL, 0, 1))")
));
$select->join(array('O', 'orders'), 
              "mytable.id = O.parent_id",
              Select::JOIN_LEFT);   
$select->group(array('mytable.id'));

$result = $dbh->selectWith($select);

假设 $dbh 是您的数据库适配器。

于 2013-09-13T17:17:40.960 回答