我在CakePHP中的關係/別名有一個奇怪的問題,現在它阻止我正確訪問我的數據。CakePHP使用別名查找查詢SQLSTATE [42S22]錯誤
我有:
- 用戶的hasMany CreatorModule(別名模塊)
- 用戶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` = '[email protected]' # <--
LIMIT 1
我想通了,錯誤的是,CakePHP的應該改變「用戶」 WHERE子句中的創造者,但沒有,即使我使用別名。如何正確完成此查詢。
此外,作爲一個相關的問題,我發現現在我已經定義了別名,我不能再在我的模型調用等中使用用戶。有沒有解決的辦法?
編輯:按照要求,這裏是我的模型代碼定義別名:
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
}
你是如何定義的別名(這不是你通常做的東西) - 請加模型文件。 (和格式化您的代碼,以便水平滾動不是必需的 – AD7six
我在相關的模型代碼中添加了 – ahjohnston25