有人可以提示我做错了什么吗?
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/