如何将列添加到 ZF2 中的 select 语句?
How do I add column to select statement in ZF2?
我正在尝试将 zf2 中的一列添加到 select 语句中。类似于下面的 link(但下面似乎只适用于 ZF1)。有没有办法在 zf2 中做到这一点?
Zend DB Selecting constants - columns that do not exist in table
下面是我试过的:
$select->columns("foo" => new \Zend\Db\Sql\Expression('"foo" as type'))
SQL 查询如下所示:
select *, 'foo' from bar
其中 foo 是所有结果的列的值和名称。尝试以上我得到 "Unknown column 'foo' in 'field list'"
非常感谢,
M
我假设 type
是别名:
试试这个:
$select->columns(array("type" => new \Zend\Db\Sql\Expression("'foo'")));
问题是方法 $select->columns()
覆盖了现有的列。
为了解决这个问题,您可以扩展自己的 "select" 并向 "add" 列添加一个新方法(作为 Select class 受保护)。
示例;
CustomSelect.php
class CustomSelect extends \Zend\Db\Sql\Select
{
/**
* @param array $columns
* @param bool $prefixColumnsWithTable
* @return $this
*/
public function addColumns(array $columns, $prefixColumnsWithTable = true) {
$this->columns = $this->columns + $columns;
$this->prefixColumnsWithTable = (bool) $prefixColumnsWithTable;
return $this;
}
}
用法:
$select = new CustomSelect();
$select->addColumns(['type' => new \Zend\Db\Sql\Expression("'foo'")]);
$select->addColumns(['*']); //This is the default value though - so adding after adding shouldn't be nessecary (except if you've used "columns()" before)
我正在尝试将 zf2 中的一列添加到 select 语句中。类似于下面的 link(但下面似乎只适用于 ZF1)。有没有办法在 zf2 中做到这一点?
Zend DB Selecting constants - columns that do not exist in table
下面是我试过的:
$select->columns("foo" => new \Zend\Db\Sql\Expression('"foo" as type'))
SQL 查询如下所示:
select *, 'foo' from bar
其中 foo 是所有结果的列的值和名称。尝试以上我得到 "Unknown column 'foo' in 'field list'"
非常感谢, M
我假设 type
是别名:
试试这个:
$select->columns(array("type" => new \Zend\Db\Sql\Expression("'foo'")));
问题是方法 $select->columns()
覆盖了现有的列。
为了解决这个问题,您可以扩展自己的 "select" 并向 "add" 列添加一个新方法(作为 Select class 受保护)。
示例;
CustomSelect.php
class CustomSelect extends \Zend\Db\Sql\Select
{
/**
* @param array $columns
* @param bool $prefixColumnsWithTable
* @return $this
*/
public function addColumns(array $columns, $prefixColumnsWithTable = true) {
$this->columns = $this->columns + $columns;
$this->prefixColumnsWithTable = (bool) $prefixColumnsWithTable;
return $this;
}
}
用法:
$select = new CustomSelect();
$select->addColumns(['type' => new \Zend\Db\Sql\Expression("'foo'")]);
$select->addColumns(['*']); //This is the default value though - so adding after adding shouldn't be nessecary (except if you've used "columns()" before)