我有一个名为Game的模型,它与Planet模型有一个hasMany关系(后者又将belongsTo定义为Game模型)。
创建我的第一个游戏记录后,我使用其starting_num_planets字段的值来尝试创建许多关联的Planet记录。 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-&gt; Game-&gt; Planet-&gt; generate_planet_data($ this-&gt; request-&gt; 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'
)
);
谁能告诉我哪里出错了?这是我第一次尝试使用相关模型,它有点出错了! :)
答案 0 :(得分:2)
问题是你在这里调用了一个缺失的函数:
$planetData = $this->Game->Planet->generate_planet_data($this->request->data['Game']['id']);
正如你所说generate_planet_data
在控制器上。所以你应该这么称呼它:
$planetData = $this->generate_planet_data($this->request->data['Game']['id']);
如评论中所述,此逻辑可能属于Planet模型。如果你把它移到那里,你就可以通过原来的方式访问它。