如何在 ZF2 中添加列以选择语句


How do I add column to select statement in ZF2?

我正在尝试将 zf2 中的列添加到 select 语句中。 类似于下面的链接(但下面似乎仅适用于 ZF1)。 有没有办法在 zf2 中做到这一点?

Zend DB 选择常量 - 表中不存在的列

以下是我尝试过的:

$select->columns("foo" => new 'Zend'Db'Sql'Expression('"foo" as type'))

SQL 查询如下所示:

select *, 'foo'  from bar

其中 foo 是所有结果的列的值和名称。尝试上述方法,我得到"Unknown column 'foo' in 'field list'"

非常感谢,米

问题是该方法$select->columns()覆盖现有列。

为了解决这个问题,你可以扩展你自己的"select",并添加一个新方法来"添加"列(因为 Select 类的列属性是受保护的)。

例;

自定义选择.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)

我假设type是别名:

试试这个:

$select->columns(array("type" => new 'Zend'Db'Sql'Expression("'foo'")));
相关文章: