How to see your Drupal View's query

Components

The other day I had an issue with a Drupal View. In some cases, the results weren't good, and I couldn't figure out why at first. My first thought was to check the query generated by this view, and that's how I quickly identified the problem.

To see the query of the View, I used the following code snippet:

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute().
 */
function MY_MODULE_views_post_execute(ViewExecutable $view) {
  $channel = 'view_query:' . $view->id();
  $message = $view->query->query();
  \Drupal::logger($channel)->debug($message);
}

My View was connected to the Search API, so the query wasn't a standard SQL query, but this method of logging the View's query will work for both regular Views and those connected to the Search API.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.