3

I'd like to add a temporary column with a fixed value to a database query. Eg a column called 'type' with a value of 'thing' for every result. I have tried using the addExpression and addField functions to do this but I'm not getting the right result.

Is this possible using db_select? I've tried the following:

$query = db_select('people', 'p')
   ->fields('p', array('id', 'date'));
$query->addField(':val AS type', array(':val'=>'thing'));

However this is executing the following query:

SELECT p.id AS id, p.date AS date
FROM 
people p

I suppose I'm trying to get drupal to do:

SELECT p.id AS id, p.date AS date, 'thing' as type
FROM 
people p
2

You just need to use an expression, e.g.

$query = db_select('people', 'p')
  ->fields('p', array('id', 'date'));

$query->addExpression(':val', 'type', array(':val' => 'thing'));

Gives:

SELECT p.id AS id, p.date AS date, :val AS type
FROM 
{people} p

The replacement for :val will be injected when you execute the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.