Get the data from the main database instead of tenant database
Opened this issue · 0 comments
devjaythakkar commented
Currently, I am facing an issue with the salon table records. In the main database, I have 3 records. However, I have only one record in the tenant database. When i switch the main database to tenant database and fetch the records from the tenant database. It give me record from the main database. It shows total 3 records. I don't know why.
Salon records in main database: 3
Salon records in tenant database: 1
class DatabaseConnection extends Connection
{
public function __construct(array $params, Driver $driver, $config, $eventManager )
{
if (isset($_SERVER['SERVER_NAME'])) {
$mainHost = $_SERVER['SERVER_NAME'];
$adminHost = $_ENV['APP_ROUTER_DOMAIN_WEB'];
if ($mainHost != $adminHost){
$parts = explode('.', $mainHost);
// Establish a temporary connection with the default parameters
$tempConnection = new Connection($params, $driver, $config, $eventManager);
$databaseUrl = $_ENV['DATABASE_URL'];
$urlComponents = parse_url($databaseUrl);
$dbName = ltrim($urlComponents['path'], '/'); // Remove leading slash
// Fetch the dynamic database configuration
$userDatabase = $tempConnection->executeQuery("SELECT * FROM $dbName.tenant_db_config WHERE db_name = :db_name", ['db_name' => $parts[0]])->fetch();
if (!$userDatabase) {
throw new NotFoundHttpException();
}
// Update connection parameters
$params['dbname'] = $userDatabase['db_name'];
$params['user'] = $userDatabase['db_user_name'] ?? $urlComponents['user'];
$params['password'] = $userDatabase['db_password'] ?? $urlComponents['pass'];
}
parent::__construct($params, $driver, $config, $eventManager);
} else {
parent::__construct($params, $driver, $config, $eventManager);
}
}
}
This way i change the database globally. When I dump($em->getConnections())
. It give me tenant database as the dbName but it give me data from the main database.