2

I am trying to add a column in zf2 to a select statement. Similar to the below link (but below only seems to work for ZF1). Is there a way to do this in zf2?

Zend DB Selecting constants - columns that do not exist in table

Below is what I tried:

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

The SQL Query looks like this:

select *, 'foo'  from bar

Where foo is the value and name of column for all results. Trying the above I get "Unknown column 'foo' in 'field list'"

Many Thanks, M

Community
  • 1
  • 1
Matt
  • 383
  • 1
  • 5
  • 20

2 Answers2

4

Problem is that the method $select->columns() overwrites the existing columns.

To counter this problem, you can extend your own "select" and add a new method to "add" columns (as the columns property of the Select class is protected).

Example;

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;
    }
}

Usage:

$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)
Rob
  • 4,927
  • 4
  • 26
  • 41
3

I'm assuming type is the alias:

try this:

$select->columns(array("type" => new \Zend\Db\Sql\Expression("'foo'")));
PrinceG
  • 982
  • 6
  • 17