Matthew Dejager
Matthew Dejager

Reputation: 329

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

Upvotes: 0

Views: 208

Answers (1)

Vernit Gupta
Vernit Gupta

Reputation: 339

Use below code :

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

Upvotes: 1

Related Questions