我在CakePHP 2.1.1项目上遇到了一个奇怪的问题。
问题是,如果我在竞争模型上调用 find(((在下面的代码中(,紧接着我在另一个模型中调用自定义方法,操作将失败并显示以下错误:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'getAddedPlayersIds' at line 1
SQL Query: getAddedPlayersIds
My CompetitionController::view(( 代码如下:
public function view($id = null) {
$this->layout = 'competition';
$this->Competition->id = $id;
if (!$this->Competition->exists()) {
throw new NotFoundException(__('Invalid competition'));
}
$active = $this->Competition->field('active', array('id' => $id));
if (!$active) {
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'competition_inactive'));
}
//THIS IS WHERE IT BECOMES STRANGE:
$competition = $this->Competition->find('first', array('conditions' => array('Competition.id' => $id)));
$addedPlayersIds = $this->CompetitionsPlayer->getAddedPlayersIds($id);
//SOME CODE INTENTIONALLY REMOVED HERE!!!
$this->set('playerShops', $playerShops);
$this->set('messages', $messages);
$this->set('competition', $this->Competition->read(null, $id));
//render() IS CALLED FOR A SPECIFIC REASON
$this->render();
}
这是CompetitionsPlayer::getAddedPlayersIds()
方法的样子:
public function getAddedPlayersIds($competitionId = null){
if(!isset($competitionId)) {
return false;
}
$this->displayField = 'player_id';
return $this->find('list', array('conditions' => array('competition_id' => $competitionId)));
}
我最初认为它以某种方式中断了,因为我将 Model::find(( 操作的返回分配给变量名称,即"竞争",但更有趣的是,如果我将 Competition::find(( 调用移动到 CompetitionPlayer::getAddedPlayersIds(( 之后,它就可以工作了!
此外,如果我重命名变量,它有时会起作用,有时不会...!?
我仍然无法弄清楚哪个是什么时候,因为我目前没有时间进一步研究这个问题。请注意,根据调试信息,通过数据库执行的查询为:
getAddedPlayersIds
这是我正在调用的函数的名称!
正如我提到的,我已经知道解决此问题的方法 - 只需交换两个调用即可。但是,如果第一个是在几秒钟之前并且没有其他方法可以执行手头的任务怎么办?
我现在只想知道为什么会这样?
这通常发生在找不到你的模型并且 Cakephp 加载默认模型时,因此没有 getAddPlayersIds 方法和蛋糕认为这是一个神奇的查询。
这是我的建议,仔细检查您的文件名和路径。
我可以看到的一个可能的问题是这一行:
$this->CompetitionsPlayer->getAddedPlayersIds($id);
那不应该是:
$this->Competition->CompetitionsPlayer->getAddedPlayersIds($id);
通过模型关联和链接。该模型是如何设置的?有什么关系?
事实证明,当使用Model::field()
函数的实现时,将递归设置为 -1 或 0。CakePHP 的核心代码是:
public function field($name, $conditions = null, $order = null) {
//Some code ommited
if ($this->recursive >= 1) {
$recursive = -1;
} else {
$recursive = $this->recursive;
}
//Some code ommited
}
所以正如所解释的,这就是问题所在。我知道这是一种性能优化,但我不确定这是一个功能还是一个问题。对我来说,这是一种奇怪的行为。