【问题标题】:CakePHP alias breaks HABTM ModelCakePHP 别名破坏了 HABTM 模型
【发布时间】:2012-11-11 11:01:12
【问题描述】:

考虑 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 关系不会保留在数据库中(传递给控制器​​中 save() 的数据是等价的)。

这不起作用:

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

    );
}

这很尴尬,因为 CakePHP docs 声明它应该可以工作。 知道为什么它不适合我吗?我错过了什么吗?

【问题讨论】:

  • 之前遇到过这个问题,也使用了可包含并收到错误说用户与 VeryUniqueAlias 没有关联。从未找到答案。

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


【解决方案1】:

使用“with”键定义连接表的模型名称。在你的情况下:

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

);

【讨论】:

  • 很遗憾,这并不能解决问题。
  • 哇,投反对票真是太可惜了。当我遇到类似问题时,添加“with”键对我有帮助。
  • 不知道谁投了反对票,也不明白为什么。无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2017-08-18
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多