CakePHP的2.1储蓄HABTM领域(CakePHP 2.1 saving HABTM fiel

2019-06-24 03:16发布

我有两个机型的用户和电影..​​如果这些与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')));
    }  
}

所以我得到一个错误,同时节省。请告诉我解决方案

Answer 1:

首先你的数据应该是这样的(前提是你要保存它通过用户模型):

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

主要的错误,我看到的是,你试图通过加入模型,你应该通过用户模型保存保存。 所以在控制器一起使用:

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

如果数据如上所述它应该罚款。 我以为我已经回答了你的问题在这里 。

希望这可以帮助。 干杯!



Answer 2:

你似乎协会有趣。 是否有你相关的HABTM与加盟两种型号模型的理由(用户,电影)? 您可以通过实现投入电影模型中的第一$ HABTM,第二$ HABTM在用户模式相同的效果。 你并不需要创建中间连接模型,蛋糕会为你做的,你只需要表。



文章来源: CakePHP 2.1 saving HABTM fields