Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email:


[CakePHP] Saving HABTM data with tables in different databases

One of the powerful features of CakePHP is the model relationships. It handles relationships seamlessly and saves/finds data of related models on its own. The most complex among the relationship is the Has And Belongs To Many, often shortened as HABTM

Recently I faced a problem in saving data for a HABTM model. The problem stemmed from the fact that the two related tables were in different databases. I wanted to relate users table in db1 with categories table in db2 and the joining table categories_users was to be kept in db2.

Normally using the following options to define HBTM association would suffice:

This didn’t work when I saved User with related Categories. It was trying to find the categories_users table in db1 while it was in the db2. I tried creating a model CategoriesUser explicitly and using the db2 database config there, but that didn’t help (of course I used “with” option so that join model is used).

Finally, taking a cue from some of the code in CakePHP core I resorted to this solution

I stopped automatic insertion of categories by unsetting it from data in the beforeSave() of User model as shown below:

Then I added an afterSave() callback to User model which inserts the category data manually

The above code, first deletes all the linking records from the join table related to the current user and then inserts the newly selected categories. This is pretty much the same what CakePHP does when saving HABTM data automatically.

Hope it is useful for you to build CRUD application using HBTM data in different databases. If anyone has a better solution do comment!

About the Author

Rita Chouhan is a Zend certified engineer, working as senior software engineer in SANIsoft.


  1. Pingback: CakePHP : signets remarquables du 29/03/2011 au 08/04/2011 | Cherry on the...

Leave a Reply