mysqlmodelcakephp-2.2

Switch between readOnly and writeOnly databases using $useDbConfig in CakePHP?


I have a master and slave database. To balance some of the load, I want all of my INSERT/UPDATE queries to go to the Master and all of my SELECT queries to go to the slave (since you cannot write to a slave without messing it up). I have the databases defined in the database.php. This is how I am trying to do the switching:

Inside the AppModel.php beforeFind(), I am setting:

$this->useDBConfig = 'readOnly';

Inside the beforeSave(), I am setting:

$this->useDBConfig = 'writeOnly';

However, after looking deeper I am wondering if the useDBConfig is a one-to-one relationship model-to-database. Meaning, maybe useDBConfig is only for pointing a single model to a single database, because this does not always work like I would expect. Sometimes an INSERT / UPDATE will attempt to run on a readOnly with readOnly permissions and fails.

If this is the case, how to I change my CakePHP application to send the requests to the appropriate databases? Should I be doing this a different way?


Solution

  • Basically, you override all of the save methods (save, saveField, saveAssociated, saveAll, UpdateAll, delete, deleteAll, etc) in the AppModel and encapsulate the parent call between two setDatasource calls.