I'm working in a multisite environment and need to switch between databases based on certain conditions. I successfully switched the active database connection using Database::setActiveConnection() in my custom code, which worked fine with direct SQL queries.

public function loadUserByExernalId(string $external_id): ?User {
    $id = '3332';

    $db = Database::getConnection();

    $query = $db->query("SELECT * FROM users WHERE uid = :uid", [':uid' => $id]);
    $users = $query->fetchAll();

and knowing that this code returns correct connection to other_db:

 dump(Database::getConnection()->getConnectionOptions()); die;

array:12 [▼
  "database" => "other_dv"
  "username" => "root"
  "password" => "root"
  "prefix" => ""
  "host" => "db"
  "port" => "3306"
  "namespace" => "Drupal\mysql\Driver\Database\mysql"
  "driver" => "mysql"
  "collation" => "utf8mb4_general_ci"
  "init_commands" => array:2 [▶]
  "autoload" => "core/modules/mysql/src/Driver/Database/mysql/"
  "pdo" => array:6 [▶]

Issue: However, when I tried to use the Entity API to load a user with the same method, it didn't work as expected.

public function loadUserByExernalId(string $external_id): ?User {
    $id = '3332';
    $user = $this->userStorage->load($id);
    dump($user); // OUTPUT: null
  • You’ll need to flush the caches after switching db connection
    – Clive
    Apr 2 at 17:27
  • @Clive even after clearing the cache i still get null with entity API Apr 2 at 17:48
  • You can't guarantee by this method that the user storage will use the alternate connection. It will have its own existing database connection already built - check the constructor for SqlContentEntityStorage. If you want to switch database connections and use the entity API, you'll probably need to be a lot smarter about it. I'd consider instead using REST API calls so you can keep your DBs on separate domains. Apr 3 at 17:03


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.