简体   繁体   中英

How to switch to second database Drupal

I am new to Drupal Developement.

I have found quite alot of information regarding adding a additional database online, I am just struggling to implement it in my existing code.

I have a file called BusinessListingDbLogic.php, that currently connects to the native Drupal database and performs queries.

I make the connection to the native database using the following code in BusinessListingDbLogic.php

    <?php

namespace Drupal\business_listing;

use Drupal\Core\Database\Database;

class BusinessListingDbLogic {

 protected $database;

 public function __construct() {
  $this->database = Database::getConnection();
  //$this->database->setActiveConnection('external');
 }

This works fine in that it connects to the native Drupal database without issues, but as soon as I uncomment //$this->database->setActiveConnection('external'); , I get

Call to undefined method

Drupal\\Core\\Database\\Driver\\mysql\\Connection::setActiveConnection() in Drupal\\business_listing\\BusinessListingDbLogic->__construct()

What am I doing wrong here? Any help or advice would be GREATLY appreciated. Kind regards, Matt

Use below code :

\Drupal\Core\Database\Database::setActiveConnection('otherdb');
$connection = \Drupal\Core\Database\Database::getConnection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM