How to switch database connections in Drupal 8
Published in
1 min readJan 26, 2018
// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('d7migration');
// Get the connection
$db = \Drupal\Core\Database\Database::getConnection();
$query = $db->select('node', 'n');
$query->fields('n', array('title', 'status'));
$users = $query->execute()->fetchAllKeyed();
// Switch back to default database
\Drupal\Core\Database\Database::setActiveConnection();