0
我在此上下谷歌搜索。我不確定我錯在哪裏,因爲我沒有得到任何錯誤。Cakephp HABTM保存-.-
我有3個表:
電影 - ID,標題,流派等
GENRES - ID,流派
GENRES_MOVIES - movie_id,genre_id
電影模式:
public $hasAndBelongsToMany = array(
'Genre' => array(
'className' => 'Genre',
'joinTable' => 'genres_movies',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'genre_id'
)
);
查看:
echo $this->Form->create('Movie', array('controller' => 'movies', 'action' => 'add', 'type' => 'file'));
echo $this->Form->input('title');
echo $this->Form->input('description', array('type' => 'textarea');
echo $this->Form->input('imdb_url');
echo $this->Form->year('release_year', 1900, date('Y'));
echo $this->Form->input('length', array('type' => 'number'));
echo $this->Form->input('genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));
echo $this->Form->input('image', array('type' => 'file'));
echo $this->Form->button('Submit');
MoviesController:
public function add()
{
/* for populating checkbox */
$this->set('genres', $this->Movie->Genre->find('list', array('fields' => array('Genre.id', 'Genre.genre'))));
if($this->request->is('post'))
{
$data_movie = array(
'title' => $this->request->data['Movie']['title'],
'description' => $this->request->data['Movie']['description'],
'imdb_url' => $this->request->data['Movie']['imdb_url'],
'release_year' => (int)$this->request->data['Movie']['release_year']['year'],
'length' => (int)$this->request->data['Movie']['length'],
'user_id' => (int)$this->Auth->user('id')
);
$data_genre = array('Genre' => array());
foreach($this->request->data['Movie']['genre'] as $genre)
array_push($data_genre['Genre'], (int)$genre);
$data = array('Movie' => $data_movie, 'Genre' => $data_genre);
$this->Movie->create();
if($this->Movie->save($data)
{
echo 'success';
}
}
}
那麼,我爲什麼懶得在movieController節省手動設置的數據,這是因爲教程告訴我的數據應該像它組織現在(在此之前,它看起來有點不同的..所以我想,這是我現在有(它看起來不錯我) http://s10.postimg.org/ikewszo95/Untitled_1.jpg
,你可以在這裏看到的形式http://marko-stimac.iz.hr/temp/movies/movies/add(雖然提交不會工作,我想這是因爲Auth組件不允許非註冊使用RS)
HM任何幫助,將greeatly感激:)
編輯 - 更新控制器
public function add()
{
$this->set('genres', $this->Movie->Genre->find('list', array('fields' => array('Genre.id', 'Genre.genre'))));
if($this->request->is('post'))
{
($this->Movie->saveAssociated($this->request->data))
{
$this->redirect('/');
$this->Session->setFlash('Success.');
}
}
}
它不工作..這就是我與調試($這個 - >請求 - > data)http://s22.postimg.org/j2i8mpvlt/Untitled_2.jpg – Marko
爲什麼它失敗了?你檢查了驗證錯誤嗎? –
我什至沒有任何驗證。有沒有$驗證,也沒有功能beforeSave在電影模型:/ – Marko