Monday, January 25, 2010

HABTM Multiple Databases

After finding many posts on HABTM relationships not supported across
databases, I thought I would share my solution. I added an option to
the HABTM config called 'useDbConfig' for specifying which database
the HABTM table is stored in. For example, I have 'system_districts'
linked to 'system_statewide_programs' in a shared database, but Cake
seems to only support HABTM in the default database. My config for the
relationship looks as follows:
var $hasAndBelongsToMany = array(
'SystemStatewideProgram' =>
array('className' => 'SystemStatewideProgram',
'joinTable' => 'system_districts_system_statewide_programs',
'foreignKey' => 'system_district_id',
'associationForeignKey' => 'system_statewide_program_id',
'conditions' => '',
'fields' => '',
'order' => 'SystemStatewideProgram.sort',
'limit' => '',
'offset' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => '',
'useDbConfig' => 'shared'
),

Here is the code I added to Cake:

//make the join tables use the default configuration, also allow
for an override
if ($assocData['useDbConfig'])
$db =& ConnectionManager::getDataSource($assocData
['useDbConfig']);
else
$db =& ConnectionManager::getDataSource('default');
$joinTbl = '`' . $db->config['database'] . '`.' . $joinTbl;


The code that adds the 'useDbConfig' option is added to libs/model/
datasources/dbo_source.php on line 1168 (Cake 1.2.5). It is in the
generateAssociationQuery() function towards the end right before the
$query is built.

I would love to see this added to Cake 1.3 if possible and would
probably help a bunch of people.

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: