I have the following SQL query, which I need to re-write using Drupal's dynamic query language. I'm new to Drupal development, could you please give me an example for the following SQL?
SELECT
node.title,
GROUP_CONCAT(field_data_field_location.field_location_value)
FROM
node
INNER JOIN field_data_field_location
ON node.nid = field_data_field_location.entity_id
INNER JOIN
(SELECT DISTINCT
entity_id
FROM
field_data_field_location
WHERE
field_location_value IN ('Berlin', 'Stuttgart')) AS IDS
ON node.nid = IDS.entity_id
GROUP BY
node.nid
What I currently have is the following:
$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');
$subquery = db_select('field_data_field_location', 'loc');
$subquery->distinct();
$subquery->fields('loc.entity_id', array('eid'));
$subquery->condition('loc.field_location_value', $locations, 'IN');
$query->join('field_data_field_location', 'l', 'n.nid = l.entity_id');
$query->addExpression('GROUP_CONCAT(l.field_location_value)', 'locations');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');
$result = $query->execute();
return $result->fetchAll();
If I execute the code, I just get nothing back from Drupal. I think the problem is the subquery. Do you have any idea how I can solve that?
$query->execute()
and all that? How do you fetch your data? That's an important part of code, too!$result = $query->execute();
add something likekpr( (string) $query);
- this will output your query, as a string, using Devel module. And you'll be able to confirm it is really what you wanted it to be. Or not.