我有一個叫做Game的模型,它與Planet模型有一個hasMany關係(它又有一個belongsTo被定義迴游戲模型)。CakePHP模型關聯HasMany - 保存錯誤
在創建我的第一個遊戲記錄時,我使用其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 = $這個 - >遊戲 - > Planet-> generate_planet_data($這 - >請求 - >數據[ '遊戲'] [ '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'
)
);
誰能告訴什麼錯?這是我第一次嘗試使用關聯模型,並且它有點錯誤! :)
函數generate_planet_data聲明在哪裏? –
這是在PlanetsController中。 (我剛剛閱讀它應該可能在Planet模型中,但我認爲這不會解決我的問題,即使它是「更好」的MVC設計... – Jimbo
看到我的答案希望這會起作用 –