我正在谷歌上下搜索。我不知道我哪里出错了,因为我没有任何错误。
我有3张桌子:
电影 - 身份,头衔,流派等
GENRES - id,genre
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组件不允许非注册用户)
嗯,任何帮助都会得到非常感谢:)
编辑 - 更新控制器
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.');
}
}
}
答案 0 :(得分:0)
不要修改数据,即摆脱这些行
$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->saveAssociated($this->request->data) {
...
修改强>
修改您的表单,更改此
echo $this->Form->input('genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));
到这个
echo $this->Form->input('Genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));