Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select from Drupal with alias

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?

like image 906
Eduard Luca Avatar asked Sep 04 '11 15:09

Eduard Luca


1 Answers

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');
like image 98
loganfsmyth Avatar answered Nov 16 '22 15:11

loganfsmyth