Answers:
此操作与Drupal 7中的操作相同,您可以在settings.php文件中添加数据库凭据。
$databases['default']['default'] = array(
'database' => 'drupal8',
'username' => 'username',
'password' => 'password',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
$databases['external']['default'] = array(
'database' => 'external',
'username' => 'username',
'password' => 'password',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
现在,您将有两个连接选项,默认和外部。您可以使用以下方法在它们之间切换:
// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');
// Do queries...
// Switch back
\Drupal\Core\Database\Database::setActiveConnection();
Database::getConnection('external')
并避免弄乱全局状态。
除了使用检索与外部数据库的数据库连接之外Database::getConnection()
,您还可以在代码中使用依赖项注入来将连接作为依赖项进行检索,并在模块的服务YAML文件中声明您的连接:
database.external:
class: Drupal\Core\Database\Connection
factory: 'Drupal\Core\Database\Database::getConnection'
arguments: ['external']
external_database_dependent_service:
class: Drupal\MODULE\Some\Class\For\A\ServiceUsingTheExternalDatabase
arguments: ['@database.external']
非常感谢@googletorp!
这是一个稍微完整的示例-我的代码从D7数据库中选择已创建节点的用户:
\Drupal\Core\Database\Database::setActiveConnection('external');
// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();
$query = $db->select('users', 'u');
$query->fields('u', array('uid', 'name'));
$query->join('node', 'n', 'n.uid = u.uid');
$query->orderBy('uid');
$users = $query->execute()->fetchAllKeyed();
\Drupal\Core\Database\Database::setActiveConnection();