选择列invalidQueryExeption

时间:2013-09-22 15:28:17

标签: zend-framework zend-db-select

我有两个表:带有ID,名称,价格和品牌字段的产品以及带有id,name,url字段的品牌。我想从这两个表中选择两个字段。 我无法定义列并定义别名。

的productTable

...
public function fetchAll()
{

    $select = new Select;
    $select->from($this->table);
    $select->join('brand', 'product.brand = brand.id', array('name', 'url'));
    $select->columns(array('product.id', 'name', 'price'));

    $statement = $this->adapter->createStatement();
    $select->prepareStatement($this->adapter, $statement);

    $resultSet = new ResultSet();
    $resultSet->initialize($statement->execute());
    return $resultSet;
   }

消息:SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'product.product.id'

请求的良好做法是什么: 选择p.id作为id,p.name作为名称,p.price,b.id作为brandid,b.name作为品牌名称......

经过几次尝试后,我找到了这个解决方案:

public function fetchAll()
{

    $select = new Select;
    $select->from($this->table);
    $select->join(array('b' => 'brand'), 'product.brand = b.id', array('brandid' => 'id', 'brandname' => 'name', 'url'));
    $select->columns(array('id', 'name', 'price'));

    $statement = $this->adapter->createStatement();
    $select->prepareStatement($this->adapter, $statement);

    $resultSet = new ResultSet();
    $resultSet->initialize($statement->execute());
    return $resultSet;
}

我找到了如何在连接表上添加别名但是基表产品怎么样?

1 个答案:

答案 0 :(得分:1)

您可以为基表指定别名,如下所示:

$select->from( array('p' => $this->table));

如果您想同时添加列,可以这样做:

$select->from( array('p' => $this->table), array('id', 'name', 'price'));
// $select->columns(array('id', 'name', 'price')); // no need for that now

要为某些列添加别名,您可以使用:

$select->from( array('p' => $this->table), array('id' => 'pid', 'name' => 'pname', 'price'));

Doc:http://framework.zend.com/manual/1.12/en/zend.db.select.html#zend.db.select.building.from

修改:

您的代码将是:

public function fetchAll()
{
    $select = new select();
    $select->from(array('p' => $this->table), array('id','name', 'price', 'brand'));
    $select->join(array('b' => 'brand'), 'p.brand = b.id', array('name', 'url'));

    // var_dump($select->__toString()); // Use this to print the SQL query corresponding to your select object

    $statement = $this->adapter->createStatement();
    $select->prepareStatement($this->adapter, $statement);

    $resultSet = new ResultSet();
    $resultSet->initialize($statement->execute());
    return $resultSet;
}