I'm writing a module to use on a multisite setup that enables nodes to be published to another site on the same installation.
Suppose I have Site A and Site B. I want this module to provide the ability to save a given node from Site A to Site B. Naturally, the way I have the database info set up in settings.php for Site A is as follows:
$databases['default']['default'] = array (
'database' => $db_name,
'username' => $db_user,
'password' => $db_pass,
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => $db_tables,
);
$databases['site_b']['default'] = array (
'database' => 'site_b',
'username' => $db_user,
'password' => $db_pass,
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
);
...thus giving Site A the info it needs to access Site B's database.
When I execute the following code in the module via the hook_node_insert
and hook_node_update
hooks:
// Switch to Site B database
db_set_active('site_b');
// Save the node on Site B
node_save($node);
...it attempts to save the node on the current database instead, resulting in an SQL error (duplicate node ID). (Also, as a side note, I'm utilising a boolean property on the $node object to prevent the hooks and node_save() from throwing each other into an endless loop.)
I tried using drupal_get_schema(NULL, TRUE);
directly after db_set_active('site_b')
, but that made no difference. I've also cleared the cache in between every code change and test. No luck.
I don't know what's preventing it from working... maybe my $databases array is structured incorrectly?
Duplicate entry '242-0-all' for key 'PRIMARY': INSERT INTO {node_access}
. Seems to be a conflict with the node ID, which is odd because it generates a new one...$node->nid
and$node->vid
based on which site's tables were being manipulated at any given time - so basically Site A was receiving node IDs used by Site B. I think this is why it looked like it wasn't switching DBs. I added in the necessary context-aware handling of the two properties and it seems to be fine now. P.S. I didn't add this as an answer as it isn't really an answer to my original question as such, but it solved a problem further down the line. :)