php - CakePHP 别名破坏了 HABTM 模型

标签 php cakephp alias has-and-belongs-to-many cakephp-model

考虑 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/

相关文章:

CMake:如何为安装不同的目标创建别名?

php 使用另一个 php 配置的模板文件?

php - zf2 "join as"语法

mysql - SQL 查询选择和更新

cakephp - CakePHP MVC Controller 可以返回图像吗?

cakephp - 如何在 Cakephp 2.x 中获取当前数据库连接名称

mysql - MySQL 中的 SHOW COLUMNS 别名

php - Codeigniter 增加 session 超时不起作用

php - 通过 Active Directory 使用 LDAP 在 PHP 中进行身份验证

mysql - CakePHP:反引号查询和普通查询的区别