0
votes

I am a newbie to cakephp and could really use some help and suggestions!

the application I am working with currently interacts with two databases, both databases have more or less a similar schema and table structure, I have to save some information in both databases, so i have this table say "employee_information" in both databases, both tables have a set of common fields (first_name, last_name, birthday, gender etc) and some other fields specific to that database. now i have to save some information into the other database using cakephp model::save() method, previously I was normally switching data source and would use sql INSERT to do this and it was working fine, but now i really would like using cakephp conventional methods to do this, reason is that i think i am missing a great deal by not using cake's own methods ( data sanitizing in my case) i had tried switching data source and using model::save(), the method did not work, though it did not log any errors, but also did not add any record into the database.

// using following snippet in the model to save.

$this->setDataSource('secondary_database');
$this->save($this->data);
$this->setDataSource('primary_database');

Any ideas or suggestions would be highly appreciated!

Thanks!

2
$this->useTable = 'secondary_table'; book.cakephp.org/2.0/en/models/model-attributes.html#usetable. PS: you are asking for "different database table", do you want to use another "database", or another "table" within the SAME database? - Jelmer
I need to save data to another database, the tables in both databases have a same name and similar fields except for some additional fields specific to the db. - Saad Rashid

2 Answers

0
votes

You're almost there, but you need to setup two db configs and select them with useDbConfig

For example:

$this->User->save($this->data); //Saves data to default (first) database
$this->User->useDbConfig('second'); //Selects second database for next uses
$this->User->save($this->data); //Saves data to second database too

//$this->User->useDbConfig('default'); //Not needed unless you want to do staff with the default database again later in the same code.

But if I'd need to save different fields in each DB, then I'd go with different models.

0
votes

Setting custom table for the controller after switching data source worked for me. (http://api.cakephp.org/1.3/class-Model.html#_setSource)

$this->User->setDataSource('secondary_database');
$this->User->setSource('secondary_database_table');
$this->User->save($this->data,array( 'validate' => true, 'fieldList' => $fieldList // specific fields that needs to be updated. ));