Skip to content

Instantly share code, notes, and snippets.

@martsie
Created July 6, 2015 01:59
Show Gist options
  • Save martsie/8d4306b1bc0134d189ac to your computer and use it in GitHub Desktop.
Save martsie/8d4306b1bc0134d189ac to your computer and use it in GitHub Desktop.
Drupal add distinct filtering for a single field of a Views database query.
<?php
/**
* Implements hook_query_alter().
*
* This hook will make it so your Drupal views are filtered by unique on a single field value.
*
* Make sure to tag your views query first by going to 'Query Settings: settings' configuration
* in Views UI and, under 'Query Tags', adding 'MY_AWESOME_TAG' or whatever you're using.'
*/
function hook_query_alter(QueryAlterableInterface $query) {
if ($query->hasTag('MY_AWESOME_TAG')) {
$query->addJoin('INNER', 'field_data_my_unique_field', 'un', 'node.nid = un.entity_id');
$query->groupBy('un.field_my_unique_field_value');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment