You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I wanted to use the mysql write connection by default for all DB operations including selects, to prevent issues caused by replication lag in a Job that is dispatched immediately after a write operation.
For this I used the following code:
DB::usingConnection('mysql::write', function () {
// my code
});
During testing I realized that my Models and even queries executed by the DB facade still using the read connection for selects.
After did some debugging I found out it is because it works like this:
DB::usingConnection() replaces the default connection's name in the DatabaseManager
When DatabaseManager::connection() is used with default connection it doesn't get a $name param and it is resolved within a subsequent call to DatabaseManager::parseConnectionName() and then use only the first $database segment without the type to look for already created connection instance so the ::write part won't take effect.
Steps To Reproduce
Create any db connection config with both write and read type and try to directly connect to the write host using DB::usingConnection()
DB::usingConnection('mysql::write', function () {
AnyModel::first(); // This will use the read connection
});
The text was updated successfully, but these errors were encountered:
Laravel Version
10.48.4
PHP Version
8.2
Database Driver & Version
No response
Description
I wanted to use the mysql write connection by default for all DB operations including selects, to prevent issues caused by replication lag in a Job that is dispatched immediately after a write operation.
For this I used the following code:
During testing I realized that my Models and even queries executed by the DB facade still using the read connection for selects.
After did some debugging I found out it is because it works like this:
DB::usingConnection()
replaces the default connection's name in theDatabaseManager
DatabaseManager::connection()
is used with default connection it doesn't get a$name
param and it is resolved within a subsequent call toDatabaseManager::parseConnectionName()
and then use only the first$database
segment without the type to look for already created connection instance so the::write
part won't take effect.Steps To Reproduce
Create any db connection config with both write and read type and try to directly connect to the write host using DB::usingConnection()
The text was updated successfully, but these errors were encountered: