12

Is there an out-of-the-box solution for printing the query of an entity query in Drupal 8?

Right now I'm using kind of a hack, adding:

->addTag('debug')

and then in a custom module:

function mymodule_query_alter($query) {
  if ($query->hasTag('debug')) {
    mymodule_query_debug($query);
  }
}

and then the debug function:

function mymodule_query_debug($query) {

  $sql = (string) $query;
  $quoted = array();
  foreach ((array) $query->arguments() as $key => $val) {
    if (is_array($val)) {
      $val = implode(', ',$val);
    }
    $quoted[$key] = \Drupal::database()->quote($val);
  }
  $sql = strtr($sql, $quoted);
  $sql = str_replace('}', '', $sql);
  $sql = str_replace('{', '', $sql);
  print_r($sql);
  die();
}

2 Answers 2

6

For Drupal 8, there is the Devel module and the Web Profiler module. The latter module, once enabled, installs a toolbar at the bottom of the page for users with the appropriate permissions. The database button within this toolbar takes you to a inspection page that shows all database queries executed during the last request.

If you're able to trigger the entity query through any browser request, you should be able to inspect the list of DB queries for the specific entity query you're looking to debug.

0
0

To examine the SQL query that the query object uses at a particular point in its lifecycle, print the query object. To examine the arguments, look at the Array returned by the arguments() method:

echo $query;
print_r($query->__toString());
print_r($query->arguments());

More about dynamic queries at https://www.drupal.org/docs/8/api/database-api/dynamic-queries/introduction-to-dynamic-queries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.