[英]How do I add column to select statement in ZF2?
我試圖將zf2中的列添加到select語句。 與下面的鏈接類似(但下面的鏈接似乎僅適用於ZF1)。 有沒有辦法在zf2中做到這一點?
以下是我嘗試的方法:
$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類的columns屬性受到保護)。
例;
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.