我有两个模型User和Movie ..那些与UsersWatchlist相关联..
public $hasAndBelongsToMany = array('User' => array(
'className' => 'User',
'joinTable' => 'users_watchlists',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $hasAndBelongsToMany = array(
'Movie' => array(
'className' => 'Movie',
'joinTable' => 'users_watchlists',
'foreignKey' => 'user_id',
'associationForeignKey' => 'movie_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
))
我在UsersController中创建了'watchlist'动作..代码在
下面public function watchlist($id = null) {
$userid = 3;
if (!$id && $userid != 3) {
$this->Session->setFlash('Invalid Movie');
$this->redirect($this->referer(array('action' => 'listing')));
}
$this->request->data['User']['id'] = $userid;
$this->User->UsersWatchlist->create();
debug($this->User->UsersWatchlist->saveAll(array('user_id' => '2', 'movie_id' => 3)));
if ($this->User->UsersWatchlist->saveAll($this->request->data)) {
$this->Session->setFlash('The movie has been added to your watchlist', 'admin/flash_success');
$this->redirect($this->referer(array('action' => 'listing')));
} else {
$this->Session->setFlash('The movie could not be added to your watchlist. Please, try again.', 'admin/flash_error');
$this->redirect($this->referer(array('action' => 'listing')));
}
}
所以我在保存时遇到错误..请告诉我解决方案
答案 0 :(得分:4)
首先,您的数据应如下所示(假设您希望通过用户模型保存):
$this->request->data = array(
'User' => array(
'id' => '2',
),
'Movie' => array(
'Movie' => array(
(int) 0 => '3',
),
),
);
我看到的主要错误是你试图通过加入模型进行保存,你应该通过用户模型进行保存。所以在控制器中使用:
$this->User->saveAll($this->request->data)
如果数据如上所述,它应该没问题。我以为我已经回答了你的问题here。
希望这会有所帮助。 干杯!
答案 1 :(得分:2)
您的协会似乎很有趣。您是否有理由将HABTM连接模型与两个模型(用户,电影)相关联?通过将第一个$ HABTM放在Movie模型中,将第二个$ HABTM放在User模型中,可以达到相同的效果。你不需要创建中间连接模型,蛋糕会为你做,你只需要表。