php - 使用 SUM 的 ZF2 自定义数据库查询

标签 php mysql zend-framework2

有人可以提示我做错了什么吗?

public function getPaymentSumByTypeAndProject($project_id,$type) {
  $type = (int) $type;
  $project_id = (int) $project_id;
  $rowset = $this->tableGateway->select(array('total_amount' => new Expression('SUM(payment.amount)')))->where(array('type' => $type, 'project_id' => $project_id));
  $row = $rowset->toArray();
  if (!$row) {
    throw new \Exception("Busted :/");
  }
  return $rowset;
}

我想做同样的查询:

SELECT SUM(amount) FROM payment WHERE type='$type' AND project_id ='$project_id';

编辑: 我取得了很小的进步,我已经想出了如何对整个专栏求和

public function getPaymentSumByTypeAndProject($project_id, $type) {
    $type = (int) $type;
    $project_id = (int) $project_id;
    $resultSet = $this->tableGateway->select(function (Select $select) {
                $select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')))->where('type="0"');
            });
    return $resultSet;

也许有人可以帮我弄清楚如何添加条件:“WHERE type='$type' AND project_id='$project_id'”?

最佳答案

我知道这是一个老问题,但我遇到了它并想我会投入我的两分钱:

public function getPaymentSumByTypeAndProject($project_id, $type) {
    // This TableGateway is already setup for the table 'payment'
    // So we can skip the ->from('payment')
    $sql = $this->tableGateway->getSql();

    // We'll follow the regular order of SQL ( SELECT, FROM, WHERE )
    // So the query is easier to understand
    $select = $sql->select()
            // Use an alias as key in the columns array instead of
            // in the expression itself
            ->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
            // Type casting the variables as integer can take place
            // here ( it even tells us a little about the table structure )
            ->where(array('type' => (int)$type, 'project_id' => (int)$project_id));

    // Use selectWith as a shortcut to get a resultSet for the above select
    return $this->tableGateway->selectWith($select);
}

此外,可以像这样从表网关中检索适配器:

$adapter = $this->tableGateway->getAdapter();

但是当您选择使用上述方法时,您实际上不再需要它了。

关于php - 使用 SUM 的 ZF2 自定义数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605785/

相关文章:

php - 如何在php中显示图标

php - jquery php mysql - 显示所有项目时如何隐藏加载更多按钮

php - ZF2 在模型中使用 OR

zend-framework2 - 我将如何记录成功的登录

php - 如何在不使用 ZF2.. 中的任何 Controller 对象的情况下访问 module.php 中的 Controller 插件?

php - 在 PHP 中,过滤关联数组的数组

php - 在php中访问不带方括号的数组值

php - 根据两个下拉选择值获取索引页面中的图像和其他详细信息?

mysql - 从一个表中选择信息引用另一个表中的信息

mysql - 显示表状态的疯狂基数计数