I have a little problem in here. I'm new at cakephp and now have to developing a cakephp shell script to saving data into its database. The problem is, I work on default environment and need to save data into another environment. I'm using this code to switch environment:
ConnectionManager::alias($env, 'default');
It seems good since I've got right output when try to get database.
$this->out($datasource->config()['database']);
And then I load my model:
$model = $this->Model;
But It's load the model data from default
environment. Is my approach wrong? Or, there is another method to switch environment on the go with cakephp?
That should work just fine, and a quick test shows that it does. You'd probably have to show a little more context, but I guess you are loading the model (what you're showing there isn't loading but accessing) before the connection alias is being created, hence the model will use the original connection that it received when it has been instantiated.
So either make sure that you load the model afterwards, respectively that you create the alias before the model is being loaded (that is when TableRegistry::get()
is being invoked), or change the connection of the specific model on the fly in case applicable:
$connection = ConnectionManager::get($env);
$model->setConnection($connection); // use connection($connection) in CakePHP < 3.4