I have a content type called Página de área (Area page) referenced by two content type: Article and Agrupador. I have a view that displays all the Article nodes that share at least one area with an Agrupador node.
My goal is removing the duplicate nodes (I get calling $query->addWhere()
) from the view.
I already tried using the Distinct and Aggregation options in the user interface, but they didn't work for me. I'm aware that this can be achieved using hook_views_pre_render()
, but if (for example) I have 10 nodes per page and two nodes are duplicates, the view ends up showing eight nodes instead of 10.
I also tried what shown in Update view result and pager in hook_views_pre_render() and in Distinct doesn't work when sorting by field with multiple values using the following code.
/**
* Implements hook_views_query_alter().
*/
function gcaba_agrupador_views_query_alter(ViewExecutable $view, Sql $query) {
if ($view->id() == 'noticias_agrupador' && $view->current_display == 'noticias_agrupador') {
$agrupador = \Drupal::routeMatch()->getParameter('node');
if ($agrupador instanceof NodeInterface) {
$agrupador = Node::load($agrupador->id());
$areas = explode(',', $agrupador->field_area->getString());
$areasArray = array_map('intval', $areas);
$query->addWhere(0, 'node__field_area.field_area_target_id', $areasArray, 'IN');
}
}
}