How to Remove Duplicates in Drupal Views with Taxonomy Relationships

remove duplicates drupal views

When working with Drupal, one of the most powerful tools at our disposal is Views. It offers a flexible way to present content, especially when content is associated with taxonomies. However, sometimes we encounter an annoying issue: duplicates. I personally faced this challenge today.

The Problem:
I created a Drupal View named ‘resources’. In this view, I display items along with their associated taxonomy terms, thanks to the relationships I’ve established. I’ve also enabled exposed taxonomy filters, allowing users to easily filter through the content. However, I noticed an issue: some items appear multiple times because they’re linked to several taxonomy terms.

I tried the “Distinct” and “Aggregate” options in Drupal Views, hoping for a quick fix. However, they didn’t solve the problem. So, after some digging, I found a solution that worked, which I’ll share below.

How to Fix It:

  1. Add a Unique Identifier to Each Item:
    First, go to your ‘resources’ view in Drupal. Add the field Content: id to the view.
  2. Alter the View’s Query:
    Implement a custom hook to modify the query of the view. This will ensure results are grouped by the content’s unique ID.
/**
 * Implements hook_views_query_alter().
 */
function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // Target the 'resources' view.
  if ($view->id() == 'resources') {
    // Add the nid field with a groupby function.
    $query->addField('node_field_data', 'nid', '', ['function' => 'groupby']);
    // Group results by node ID.
    $query->addGroupBy('node_field_data.nid');
  }
}

In Simple Words:
What we’re doing here is simple. We tell Drupal to look at each entry in our view and group them by their unique content ID. This way, even if a piece of content is related to multiple taxonomy terms and would normally appear more than once, it will now show up only a single time.

Happy debugging!


Posted

in

,

by