1

我有两张与此事相关的表格,posts 和 postratings。模型有以下关系:

Post hasmany Postrating
Postrating belongsto Post

表模式是:

桌柱
id | user_id | post | rating_post | ratings

表评级
id | user_id | post_id | rating_post

这个想法是,如果帖子存在,用户可以对其进行评分。通过对表进行评级,该表ratings将获得一个新条目,并且该表posts将获得 ID 为 post_id 的帖子条目的更新

我的问题是,我只能在两个表中保存新条目。我用 . 试过了saveAssociated(),但结果和我用saveAll().

如果有人可以帮助我,我将不胜感激。当然,如有必要,我会提供更多信息。

提前致谢

编辑: //

这是 PostratingsController 的方法 add

public function add($id = null) {


$this->loadModel('Post');

if (!$this->Post->exists($id)) {
    throw new NotFoundException(__('Invalid post'));
    }
if ($this->request->is('post')) {
    $this->Postrating->create();
    if ($this->Postrating->save($this->request->data)) {
        if ($this->Postrating->save($this->request->data)) {
            $this->Postrating->Post->id = $id;
            $this->Postrating->Post->save($this->request->data);
            $this->Session->setFlash(__('The postrating has been saved'));
            $this->redirect(array('action' => 'index'));
        }
    } else {
        $this->Session->setFlash(__('The postrating could not be saved.'));
    }
} else {
    $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
    $this->request->data = $this->Post->find('first', $options);
}

$post = $this->Postrating->Post->find('list');
$users = $this->Postrating->User->find('list');
$this->set(compact('posts', 'users'));

$options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
$this->set('posts', $this->Post->find('first', $options));

}

4

1 回答 1

0

你确定是同时的吗?假设您rating是一个数字(例如,介于 1 和 5 之间)并且您希望将“总”评分存储在您的帖子表中。我会做类似的事情(伪代码)

if($this->Rating->saveRating($user_id, $post_id, $rating)) {
    $this->Rating->Post->id = $post_id; // update instead of insert
    $this->Rating->Post->updateRating($rating);
}

例如:

  • 用户评分 评分为 5 的帖子
  • 检查用户是否已经评价了这篇文章
  • 保存评分
  • 使用新评级 ( existing_rating + new_rating)更新 Post 表
于 2013-03-02T13:11:43.113 回答