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