How to select from Drupal with alias

13.7k views Asked by At

I want to get 1 column from a table in Drupal as 2 aliases. Something like this but with Drupal's query methods.:

SELECT name AS label, name AS value FROM node WHERE 1

This Drupal code doesn't set the right alias:

$query = db_select('node', 'node');
$query->fields('node', array('label' => 'name','value' => 'name'));

It returns something like: [name] => Science [node_name] => Science

Is there any way to set the alias?

1

There are 1 answers

1
loganfsmyth On BEST ANSWER

The 'fields' method does not allow you to set aliases. If you look at the docs, the second argument for fields is an indexed array, so numbers only.

http://api.drupal.org/api/drupal/includes--database--select.inc/function/SelectQuery::fields/7

If you need aliases, then you need to use 'addField'.

http://api.drupal.org/api/drupal/includes--database--select.inc/function/SelectQuery::addField/7

$query = db_select('node', 'n');

$query->addField('n', 'name', 'label');
$query->addField('n', 'name', 'value');