Score:2

Eliminate results from a relationship (add an ON condition to JOIN)

de flag

I need to add an ON condition to a views JOIN. I cannot use a contextual filter, as it will filter out results altogether, and I need to get a result regardless (there are other joins). So I need to ensure the filter happens on the JOIN, and not as a WHERE condition.

To be more specific, I want to show a value when no relationship exists. The relationship is from one NODE type to another NODE of the same type, and I don't want the current node retrieved. So the ON condition should be AND join_table.id != original_table.id.

I'm new to altering views queries. Can anyone provide assistance either on how to add an ON condition to a Views query either through the admin UI (if possible) or through a query alter?

Thank you

sonfd avatar
in flag
Does this help? https://drupal.stackexchange.com/a/251700/48114
Jaypan avatar
de flag
Almost, but not. It shows how to add an 'ON' condition, but the condition is for a fixed value, where I the condition to be on another table column.
sonfd avatar
in flag
Can you use some of the other options listed here: https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21join%21JoinPluginBase.php/property/JoinPluginBase%3A%3Aextra/8.2.x
Jaypan avatar
de flag
Thank you for the additional information. I played with it for a while, but I don't see any combination that allows me to get the right tables and columns referenced in the query, particularly as `value` is required, but I'm not working with a value, I'm working with a column name.
Score:3
de flag

Thanks to help from sonfd above, I was able to come up with a solution of sorts. I was not able to compares the two columns as I was trying to, but I was able to use $view->args to come up with the result I wanted.

To answer the question on how to add an additional ON condition to JOIN, you can do the following:

function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == VIEW_ID && $view->current_display === DISPLAY_ID) {
    $table = $query->getTableInfo(TABLE_NME);
    $table['join']->extra = empty($table['join']->extra) ? [] : $table['join']->extra;
    $table['join']->extra[] = [
      'field' => FIELD_NAME,
      'operator' => '!=',
      'value' => VALUE, // In my case $view->args[0],
    ];
  }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.