8.5.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.0.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.1.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.2.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.3.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.4.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
8.6.x database.api.php hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query)
7.x system.api.php hook_query_alter(QueryAlterableInterface $query)

Perform alterations to a structured query.

Structured (aka dynamic) queries that have tags associated may be altered by any module before the query is executed.

Parameters

$query: A Query object describing the composite parts of a SQL query.

See also

hook_query_TAG_alter()

node_query_node_access_alter()

AlterableInterface

SelectInterface

Related topics

3 functions implement hook_query_alter()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

database_test_query_alter in core/modules/system/tests/modules/database_test/database_test.module
Implements hook_query_alter().
taxonomy_test_query_alter in core/modules/taxonomy/tests/modules/taxonomy_test/taxonomy_test.module
Implements hook_query_alter().
views_test_data_views_query_alter in core/modules/views/tests/modules/views_test_data/views_test_data.views_execution.inc
Implements hook_views_query_alter().

File

core/lib/Drupal/Core/Database/database.api.php, line 403
Hooks related to the Database system and the Schema API.

Code

function hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query
    ->hasTag('micro_limit')) {
    $query
      ->range(0, 2);
  }
}

Comments

lykyd’s picture

use Drupal\Core\Database\Query\AlterableInterface;

function MYMODULE_query_alter(AlterableInterface $query) {
  if (isset($query->alterMetaData['view'])) {
    if($query->alterMetaData['view']->id() == 'replace_by_view_machine_name') {
      // Group by UID to remove duplicates from View results
      $query->groupBy('users_field_data.uid');
      // If multilingual site, you should add the following :
      // $query->groupBy('users_field_data.langcode');
    }
  }
}