Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Drupal 8 Database query

Drupal 8 Database query
, by
Drupal 8 Database query
1 answer
votes: 1365
Answer

You would use the database abstraction layer.

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute();

As for executing the query, you can also fetch results in various ways.

Examples:

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAll();


$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAllAssoc('nid');

If you are within a class, you should inject the appropriate classes in your constructor instead of use the static Drupal container. But since you are in a preprocess function, \Drupal::database() is fine.

From core/lib/Drupal.php:

 /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
    return static::getContainer()->get('database');
  }

Depending on your use case(s), you can also leverage EntityQuery:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$results = $query->execute();

Please note that you may want to use node_field_data table instead of node, but your query is pretty generic so it is hard to tell without a better query.

Example, get all nodes of type that are published:

$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->addField('nfd', 'nid');
$query->condition('nfd.type', 'blablabla');
$query->condition('nfd.status', 1);
$results = $query->execute();

Or:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$query->condition('status', 1);
$results = $query->execute();

Drupal 8 Documentation:
https://www.drupal.org/docs/8/api/database-api