Use database replica target in entity query
When you have a database replica configured you can run queries against it as following
$connectionReplica = \Drupal::service('database.replica');
$connectionReplica->select(...);
...
or
$connectionReplica = \Drupal\Core\Database\Database::getConnection('replica', 'default');
$connectionReplica->select(...);
...
or
$database = \Drupal::database();
$result = $database->query("SELECT ...", [], [
'target' => 'replica',
'fetch' => PDO::FETCH_ASSOC,
]);
To use it with EntityQuery you need to do following
Define a new service
services:
myservice.entity.query.mysql_replica:
class: Drupal\Core\Entity\Query\Sql\QueryFactory
arguments: ['@database.replica']
and use it as bellow
/** @var \Drupal\Core\Entity\Query\Sql\QueryFactory $queryFactory */
$queryFactory = \Drupal::service('myservice.entity.query.mysql_replica');
$entityType = \Drupal::entityTypeManager()->getDefinition('node');
$query = $queryFactory->get($entityType, 'AND');
$query->condition(...);
...
Alternatively, it is possible to override globally the core's `entity.query.sql` service as following
services:
mysql.entity.query.sql:
class: Drupal\Core\Entity\Query\Sql\QueryFactory
arguments: ['@database.replica']