CakePHP 2.3-如何同时添加和更新两个不同的表

CakePHP 2.3-如何同时添加和更新两个不同的表,cakephp,saving-data,cakephp-2.3,Cakephp,Saving Data,Cakephp 2.3,我有两个与此相关的表格,posts和postratings。这些模型具有以下关系: Post有许多postgrating postgrating belongsto Post 表架构包括: 表格帖子 id |用户| id |发布|评级|发布|评级 表格评级 id |用户id |发布id |评级|发布 其想法是,如果存在帖子,用户可以对其进行评分。通过对表评级获取一个新条目,表发布获取一个更新,更新后条目的id为post\u id 我的问题是,我只能在两个表中保存新条目。我已经用saveAssoc

我有两个与此相关的表格,posts和postratings。这些模型具有以下关系:

Post有许多postgrating

postgrating belongsto Post

表架构包括:

表格帖子
id |用户| id |发布|评级|发布|评级

表格评级
id |用户id |发布id |评级|发布

其想法是,如果存在帖子,用户可以对其进行评分。通过对表
评级
获取一个新条目,表
发布
获取一个更新,更新后条目的id为post\u 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));

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

例如:

  • 用户评分为5分的帖子
  • 检查用户是否已经对此帖子进行了评分
  • 保存评级
  • 使用新评级更新Post表(
    现有评级+新评级

什么是
评级\u帖子
评级
?表单是否包含帖子的“id”?此外,由于您不更新帖子本身,您只需更新/插入评分表/模型中的数据,“rating_post”是所有评分的总和ratings'是@thaJeztah的收视率是的,我通过postratings/view/ID获取帖子的ID。我想更新rating_post和ratings字段中的表帖子,以便我可以列出收视率最好的帖子。因此,也有必要更新posts表,但这些字段不是用户输入的,也不是表单数据的一部分。看看@Ross的答案,因为这是应该做的。发布评级的用户不能直接编辑帖子中的数据,只能发布评级。应用程序逻辑随后应更新计算的总数ratings@thaJeztah帖子的字段对用户隐藏。它们由posts表中post条目的值填充。我已经发布了add方法。还是一样。在这种情况下,将保存后评价,但不会更新后评价。上述方法是正确的方法之一。你不能不考虑发生了什么就直接通过
$this->request->data
save()
,数据必须是正确的格式和正确的键。发布转储的
$this->request->data
if($this->Rating->saveRating($user_id, $post_id, $rating)) {
    $this->Rating->Post->id = $post_id; // update instead of insert
    $this->Rating->Post->updateRating($rating);
}