0

I'm in the process of transferring a script over to Drupal 7 and have a variable field name in the query. From a bit of research, it looks like the only way to execute the query is via a structured query. Here is essentially what I was going for:

db_query("SELECT '$variable_field_name1', '$variable_field_name2',
POW((lat - :lat), 2) + POW((:lng - lng), 2) AS distance
FROM table ORDER BY distance
LIMIT 1", array(':lat' => $lat, ':lng' => $lng));

Here's where I get stuck (can't find documentation on the AS statement):

$query = db_select('table', 't');
$query->fields('t', array("$variable_field_name1", "POW((lat - $lat), 2) 
                                    + POW(($lng - lng), 2) AS distance"));
$query->orderBy('distance', 'ASC');
$query->range(0, 1);
$result = $query->execute();
4

1 回答 1

0

只需使用 addExpression() 来设置这种查询。

$query = db_select('table', 't');
$query->fields('t', array($variable_field_name1, $variable_field_name2));
$query->addExpression(
  'POW((lat - :lat), 2) + POW((:lng - lng), 2)',
  'distance',
  array(':lat' => $lat, ':lng' => $lng)
);
$query->orderBy('distance', 'ASC');
$query->range(0, 1);
$result = $query->execute();

关于 addExpression() 的文档可以在https://drupal.org/node/1848358找到。

于 2013-11-04T21:24:02.513 回答