Ticket 105 - Problem with saving habtm between different db-schemas #69

wants to merge 4 commits into


None yet
2 participants

rchavik commented May 10, 2011


Please consider merging this branch. It fixes the problem logged in lighthouse ticket #105

The second commit is required to avoid the "Unknown table 'foo' in MULTI DELETE" error as discussed in this blog post

rchavik added some commits May 10, 2011

Include actual table name in DELETE statement
This avoids mysql error 1109: Unknown table 'foo' in MULTI DELETE

rchavik commented May 10, 2011

Forgot to mention that 'with' key is required in the relationship declaration.


lorenzo commented May 10, 2011


Also I would not assume that both tables can be accessed using the same connection. So you should call the insert on the datasource fro the other model.


rchavik commented May 11, 2011

Since the HABTM has defined 'with' key, it would use the value from the join model. eg:

// models/user.php
class User {
    var $hasAndBelongsToMany = array(
        'Group' => array(
            'with' => 'GroupsUser',


// models/GroupsUser.php
class GroupsUser extends AppModel {
    var $name = 'GroupsUser';
    var $useDbConfig = 'otherdb';

cake will correctly use 'otherdb' when inserting groups_users records.

For tests, i'll try to update existing and write new ones up. This broke a lot of tests since it compares:

select * from foo;


select * from mydatabase.foo;

rchavik commented May 11, 2011

Let me try to rework this. I'm closing this pull request for now.

@rchavik rchavik closed this May 11, 2011

@rchavik rchavik reopened this May 12, 2011


rchavik commented May 12, 2011


Can you comment on the additional commit rchavik/cakephp@4f12dde ? The deletions and insertions are now using the otherdb datasource.

rchavik/cakephp@211976f introduces another parameter to fullTableName which may have bigger effect on the framework. I have adjusted test cases.

At this point, all existing model and behavior tests passes.

If you think this approach is sound, I'll add more tests for this use-case, rework the patch properly and remove the clumsy 'if' conditions wherever possible.

This is looking better, I would change two things

  1. Get the other model's datasource with $db = $this->{$withModel}->getDataSource();
  2. Write a test case for this, please?

rchavik replied May 22, 2011


Glad that I'm not too far off.

I'll include your suggestions and tests. Currently reworking this in rchavik/cakephp@ticket_105-reworked. I'll create another pull requests when it looks better.

Thanks again for your input


rchavik commented May 22, 2011

Obsolete. See #92

@rchavik rchavik closed this May 22, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment