ZF2查询在列函数中删除表名

时间:2015-10-07 13:47:21

标签: php mysql zend-framework

我正在尝试将我的示例中的查询转换为ZF2查询。我差点搞定了,但是列(AS)函数通过在我的计算前添加表名来搞乱它。

工作查询示例;

SELECT id, city, ( 6371 * acos( cos( radians(51.5009745484064) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(3.6766170173753) ) + sin( radians(51.5009745484064) ) * sin( radians( lat ) ) ) ) AS distance 
FROM zipcodes 
HAVING distance < 100 
ORDER BY distance desc 
LIMIT 0 , 20;

ZF2查询输出;

SELECT "zipcodes"."id" AS "id", "zipcodes"."city" AS "city", "zipcodes"."(6371 * acos(cos(radians(51.5009745484064)) * cos(radians(lat)) * cos(radians(lng)-radians(3.6766170173753)) + sin(radians(51.5009745484064)) * sin(radians(lat))))" AS "distance" 
FROM "zipcodes" 
HAVING distance < '25' 
ORDER BY "distance" 
ASC LIMIT '10'

ZF2查询

# Expression
$having = new \Zend\Db\Sql\Having();
$having->expression('distance < ?', $radius);

# Select
$select = new Select();
$select->from($this->table)
        ->columns(array('id', 'city', 'distance' => '(6371 * acos(cos(radians(51.5009745484064)) * cos(radians(lat)) * cos(radians(lng)-radians(3.6766170173753)) + sin(radians(51.5009745484064)) * sin(radians(lat))))'))
        ->having($having)
        ->order($order)
        ->limit($limit);

$rowset = $this->selectWith($select);
return $rowset->current();

1 个答案:

答案 0 :(得分:1)

始终阅读源代码。这会节省你的时间。

/**
 * Specify columns from which to select
 *
 * Possible valid states:
 *
 *   array(*)
 *
 *   array(value, ...)
 *     value can be strings or Expression objects
 *
 *   array(string => value, ...)
 *     key string will be use as alias,
 *     value can be string or Expression objects
 *
 * @param  array $columns
 * @param  bool  $prefixColumnsWithTable
 * @return Select
 */
public function columns(array $columns, $prefixColumnsWithTable = true)
{
    $this->columns = $columns;
    $this->prefixColumnsWithTable = (bool) $prefixColumnsWithTable;
    return $this;
}

从那里开始,只需这样做:

$select->from($this->table)
        ->columns(array('id', 'city', 'distance' => '(6371 * acos(cos(radians(51.5009745484064)) * cos(radians(lat)) * cos(radians(lng)-radians(3.6766170173753)) + sin(radians(51.5009745484064)) * sin(radians(lat))))'), false)
        ->having($having)
        ->order($order)
        ->limit($limit);