4
votes

Consider the following HABTM relation in CakePHP 2.2.3:

class User extends AppModel
{    
    public $hasAndBelongsToMany = array(
        'Role' => array(
            'className' => 'Role',
            'joinTable' => 'roles_users',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'role_id',
        )

    );
}

This works fine, but when using an alias like VeryUniqueAlias instead of Role and changing the UsersController accordingly, the m:n relation is not persisted in the database (the data passed to save() in the controller are equivalent).

This does not work:

class User extends AppModel
{    
    public $hasAndBelongsToMany = array(
        'VeryUniqueAlias' => array(
            'className' => 'Role',
            'joinTable' => 'roles_users',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'role_id',
        )

    );
}

This is awkward, since the the CakePHP docs state that it should work. Any idea why it's not working for me? Did I miss something?

1
Had this problem before, also using containable and getting errors saying User is not associated with VeryUniqueAlias. Never found an answer.472084

1 Answers

0
votes

Use the 'with' key to define the name of the model for the join table. In your case:

public $hasAndBelongsToMany = array(
    'VeryUniqueAlias' => array(
        'className' => 'Role',
        'joinTable' => 'roles_users',
        'with' => 'RolesUser',    // first model pluralized
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'role_id',
    )

);