In my task I need to get the distinct number of the nodes of some content type. How can I do it?

$query = $this->connection->select('node', 'node')->condition('node.type', $type);
$query->innerJoin('taxonomy_index', $id,  "$id.nid = node.nid  AND $id.status = 1");
$count = intval($query->execute()->fetchField());

As the node may have multiple values for the field, in the end it counts all nodes and produces the wrong output. Therefore I need to get distinct number of nodes.

Just adding $query->distinct(); doesn't bring anything. Could you please help me how can I solve the issue?


You can use Drupal EntityQuery class like this:

$count = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', $type)
  • maybe I should have mentioned in the description that i perform an innerjoin as well with "taxonomy_index" table, and it results in wrong counting. That's why I am searching a way to reduce duplicates – badm Sep 18 '18 at 8:17
  • Then please update the question and include the missing code so that others can help as well – Ismail Cherri Sep 18 '18 at 8:18

If you want to retrieve distinct number of the nodes of content type $type.
Try this.

use Drupal\Core\Database\Database;

//- Retrieves a \Drupal\Core\Database\Connection which is a PDO instance
  $connection = Database::getConnection();
    $query = $connection->select('node', 'node')
        ->fields('node', array('nid'))
        ->condition('node.type', $type, '=')
        //- Force filtering of duplicate records in the result set.

    $count = $query->fetch(\PDO::FETCH_NUM);

Ps: you still have to add Your desired innerJoin to the query take a look to Select::innerJoin .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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