我有一个名为 Game 的模型,它与 Planet 模型具有 hasMany 关系(而该模型又定义回 Game 模型的 belongsTo )。
在创建我的第一个游戏记录时,我使用它的starting_num_planets 字段的值来尝试创建那么多关联的行星记录。GamesController 通过调用 PlanetsController 中的一个函数来执行此操作,每次调用该函数时,都会返回一个与 Planet 模型匹配的数组,并且应该是可保存的,这是 GamesController 尝试做的下一件事。
游戏记录创建得很好,但在我试图访问第二个控制器的功能时,我显然得到了一个无效的 SQL 语法错误。这很奇怪,因为我直到几行之后才尝试保存。
以下是 GamesController 的代码:
public function newgame() {
if ($this->request->is('post')) {
$this->Game->create();
if ($this->Game->save($this->request->data)) {
// Add the 'id' element to the Game array and put the whole game record on the session
$this->request->data['Game']['id'] = $this->Game->getLastInsertID();
$this->Session->write('Game', $this->request->data);
// Create the number of planet records indicated by start_num_planets
$count = 0;
$planets = array();
while ($count < $this->request->data['Game']['starting_num_planets']) {
$planetData = $this->Game->Planet->generate_planet_data($this->request->data['Game']['id']);
$planets[$count] = $planetData;
$this->Game->Planet->create();
$this->Game->Planet->save($planetData);
$count++;
}
$this->redirect(array('action' => 'main'));
} else {
$this->Session->setFlash('There was a problem creating the game.');
}
}
}
在此行的行号处:
$planetData = $this->Game->Planet->generate_planet_data($this->request->data['Game']['id']);
我正进入(状态:
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 'generate_planet_data' at line 1
SQL Query: generate_planet_data
我不知道为什么,我很害怕。
这是在 PlanetsController 中调用的函数:
public function generate_planet_data($gameId) {
$planetNames = array(1 => 'name1', 2 => 'name2', 3 => 'name3', 4 => 'name4');
$planetImages = array(1 => '01', 2 => '02', 3 => '03', 4 => '04');
$planetData = array();
// game_id is the foreign key, do I have to explicitly state that in the model?
$planetData['Planet']['game_id'] = $gameId;
$planetData['Planet']['planet_name'] = $planetNames[rand(1,10)];
$planetData['Planet']['planet_image_file'] = $planetImages[rand(1,4)];
return $planetData;
}
Game.php 中的模型关联很简单:
var $hasMany = array(
'Planet' => array(
'className' => 'Planet'),
'Player' => array(
'className' => 'Player'
)
);
谁能告诉我出了什么问题?这是我第一次尝试使用关联模型,结果有点不对劲!:)