Running queries

Now that we have some tables to work with, let's take a look at how we can run queries against them. If you are following along, for testing purposes, feel free to add some dummy data into the tables via the database management tool of your choice. We will look at INSERT statements soon, but before that, we will need to talk about the more common types of queries you'll run--SELECT.

Queries using the Drupal 8 database abstraction layer are run using a central database connection service--database. Statically, this can be accessed via a shortcut:

$database = \Drupal::database();

This service is a special one compared to the ones we saw before, because it is actually created using a factory:

 database: class: Drupal\Core\Database\Connection ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.