3

我有两个模型 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 中创建了“监视列表”操作。代码如下

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')));
    }  
}

所以我在保存时遇到错误..请告诉我解决方案

4

2 回答 2

4

首先你的数据应该是这样的(如果你想通过用户模型保存它):

$this->request->data = array(
    'User' => array(
        'id' => '2',
    ),
    'Movie' => array(
        'Movie' => array(
            (int) 0 => '3',
        ),
    ),
);

我看到的主要错误是您试图通过联接模型进行保存,而您应该通过用户模型进行保存。所以在控制器中使用:

$this->User->saveAll($this->request->data)

如果数据如上所述,它应该没问题。我想我已经在这里回答了你的问题。

希望这可以帮助。干杯!

于 2012-05-04T10:28:40.310 回答
2

你的联想似乎很有趣。您将 HABTM 连接模型与两个模型(用户、电影)相关联是否有原因?您可以通过将第一个 $HABTM 放在 Movie 模型中,将第二个 $HABTM 放在 User 模型中来实现相同的效果。您不需要创建中间连接模型,cake 会为您完成,您只需要表格。

于 2013-03-27T15:17:45.097 回答