W3cubDocs

/Drupal 8

protected function Select::prepareCountQuery

protected Select::prepareCountQuery()

Prepares a count query from the current query object.

Return value

\Drupal\Core\Database\Query\Select A new query object ready to have COUNT(*) performed on it.

File

core/lib/Drupal/Core/Database/Query/Select.php, line 718

Class

Select
Query builder for SELECT statements.

Namespace

Drupal\Core\Database\Query

Code

protected function prepareCountQuery() {
  // Create our new query object that we will mutate into a count query.
  $count = clone($this);

  $group_by = $count->getGroupBy();
  $having = $count->havingConditions();

  if (!$count->distinct && !isset($having[0])) {
    // When not executing a distinct query, we can zero-out existing fields
    // and expressions that are not used by a GROUP BY or HAVING. Fields
    // listed in a GROUP BY or HAVING clause need to be present in the
    // query.
    $fields = &$count->getFields();
    foreach (array_keys($fields) as $field) {
      if (empty($group_by[$field])) {
        unset($fields[$field]);
      }
    }

    $expressions = &$count->getExpressions();
    foreach (array_keys($expressions) as $field) {
      if (empty($group_by[$field])) {
        unset($expressions[$field]);
      }
    }

    // Also remove 'all_fields' statements, which are expanded into tablename.*
    // when the query is executed.
    foreach ($count->tables as &$table) {
      unset($table['all_fields']);
    }
  }

  // If we've just removed all fields from the query, make sure there is at
  // least one so that the query still runs.
  $count->addExpression('1');

  // Ordering a count query is a waste of cycles, and breaks on some
  // databases anyway.
  $orders = &$count->getOrderBy();
  $orders = array();

  if ($count->distinct && !empty($group_by)) {
    // If the query is distinct and contains a GROUP BY, we need to remove the
    // distinct because SQL99 does not support counting on distinct multiple fields.
    $count->distinct = FALSE;
  }

  // If there are any dependent queries to UNION, prepare each of those for
  // the count query also.
  foreach ($count->union as &$union) {
    $union['query'] = $union['query']->prepareCountQuery();
  }

  return $count;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Query!Select.php/function/Select::prepareCountQuery/8.1.x