Drupal 8 Query Questions Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?

How do I know when I can chain my query methods and when I can not? For example

$db = \Drupal\core\Database\Database::getConnection();

$query = $db-&gt;select('node', 'n')
  -&gt;fields('n', ['nid'])
  -&gt;condition('type', 'blog');

$results = $query-&gt;execute()
  -&gt;fetchAll();


vs

$db = \Drupal\core\Database\Database::getConnection();

$query = $db-&gt;select('node', 'n');
$query-&gt;fields('n', ['nid']);
$query-&gt;fields('nb', ['body_value']);
$query-&gt;join('node__body', 'nb', 'n.nid = nb.entity_id');
$query-&gt;condition('n.type', 'blog');

$results = $query-&gt;execute()
  -&gt;fetchAll();
Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?


Yes. The former returns a correctly instantiated service object, with all required dependencies automatically injected. You would need to load up all the relevant services yourself and inject them manually if using the latter method.


  How do I know when I can chain my query methods and when I can not?


There are 2 common approaches:


Read the docs for the methods you're using.
Use an IDE with good code completion.