0

我在 CakePHP 中的关系/别名有一个奇怪的问题,现在它阻止我正确访问我的数据。

我有:

  • 用户 hasMany CreatorModule(Module 的别名)
  • 用户 HABTM LearnerModule(模块的别名)
  • 模块属于创建者(用户的别名)
  • 模块 HABTM 学习者(用户的别名)

我试图打电话给:

$id = $this->Module->User->findByEmail($email);
$modules = $this->Module->findByUserId($id['User']['id']);

生成的查询不正确 - 表别名错误。我不确定以上哪一项是负责任的,但我得到:

SELECT
    `Creator`.`id`,
    `Creator`.`email`,
    `Creator`.`organization`,
    `Creator`.`name`,
    `Creator`.`password`,
    `Creator`.`verified`,
    `Creator`.`vcode`
FROM
    `snurpdco_cake`.`users` AS `Creator` 
WHERE
    `User`.`email` = 'foo@example.com' # <--
LIMIT 1

我发现错误是 CakePHP应该将 WHERE 子句中的“用户”更改为 Creator,但即使我使用别名也不会。如何正确完成此查询。

此外,作为一个相关问题,我发现既然我已经定义了别名,我就不能再在我的模型调用等中使用用户。有没有解决的办法?

编辑:根据要求,这是我定义别名的模型代码:

class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
    'OwnedModule' => array(
        'className' => 'Module',
        'foreignKey' => 'user_id',
        'dependent' =>  true
        ));
public $hasAndBelongsToMany = array(
    'LearnerModule' => array( 
       'className'              => 'Module',
       'joinTable'              => 'modules_users',
       'foreignKey'             => 'user_id',
       'associationForeignKey'  => 'module_id',
       'unique'                 => 'keepExisting',
    ));
//The rest of the Model
} 
//Different file, condensed here for spacing 
class Module extends AppModel {
public $name = 'Module';
public $belongsTo = array(
    'Creator' => array(
        'className' => 'User'));    
public $hasAndBelongsToMany = array(
    'Learner' => array(
       'className'              => 'User',
       'joinTable'              => 'modules_users',
       'foreignKey'             => 'module_id',
       'associationForeignKey'  => 'user_id',
       'unique'                 => 'keepExisting',
    ));
//The rest of the Model
}
4

1 回答 1

0

尝试

$id = $this->Module->Creator->find('first', 
          array('conditions' => array('Creator.email' => $email)
      );
$modules = $this->Module->findByCreatorId($id['User']['id']);
于 2013-01-22T02:19:18.617 回答