How to use Master/Slave doctrine2 configurations from Symfony2 Console commands
You have to make sure your command doesn't call any action that lets doctrine choose the master connection.
Important for the understanding of the MasterSlaveConnection
should be how and when it picks the slave or master.
- picks Slave if Master was never picked before and ONLY if 'getWrappedConnection' or 'executeQuery' is used.
- Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint', 'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or 'prepare' is called.
- If master was picked once during the lifetime of the connection it will always get picked afterwards.
- One slave connection is randomly picked ONCE during a request.
(MasterSlaveConnection API)
I ended up on this question when I was looking for a way to query either my master for writting or my slaves for reading.
Here is the magic:
Write operations (use master):
$em->getConnection->executeUpdate(...);
Read operations (use slaves):
$em->getConnection->executeQuery(...);