考虑 CakePHP 2.2.3 中的以下 HABTM 关系:
class User extends AppModel
{
public $hasAndBelongsToMany = array(
'Role' => array(
'className' => 'Role',
'joinTable' => 'roles_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'role_id',
)
);
}
这工作正常,但是当使用像 VeryUniqueAlias
这样的别名而不是 Role
并相应地更改 UsersController 时,m:n 关系不会保留在数据库中(传递给 Controller 中 save()
的数据是等效的)。
这不起作用:
class User extends AppModel
{
public $hasAndBelongsToMany = array(
'VeryUniqueAlias' => array(
'className' => 'Role',
'joinTable' => 'roles_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'role_id',
)
);
}
这很尴尬,因为 CakePHP docs声明它应该工作。 知道为什么它对我不起作用吗?我错过了什么吗?
最佳答案
使用“with”键定义连接表的模型名称。在你的情况下:
public $hasAndBelongsToMany = array(
'VeryUniqueAlias' => array(
'className' => 'Role',
'joinTable' => 'roles_users',
'with' => 'RolesUser', // first model pluralized
'foreignKey' => 'user_id',
'associationForeignKey' => 'role_id',
)
);
关于php - CakePHP 别名破坏了 HABTM 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13522993/