2013-03-02 35 views
0

我有两个表格与这个问题,帖子和邮寄相关。该机型具有以下关系:CakePHP 2.3 - 如何同时添加和更新两个不同的表格

Post hasmany Postrating
Postrating belongsto Post

表架构是:

表帖
id | user_id | post | rating_post | ratings

表中的评级
id | user_id | post_id | rating_post

的我dea是,如果一个帖子存在,用户可以评价它。通过评分表ratings获得新条目和表posts在ID为post_id的帖子条目上获得更新

我的问题是,我只能保存两个表中的新条目。我试过saveAssociated(),但结果与我使用saveAll()的结果相同。

如果有人能帮助我,我将不胜感激。如有必要,我当然会提供进一步的信息。

在此先感谢

编辑://

这里是方法的PostratingsController

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

}

+0

什么是'rating_post'和'ratings'? – Ross 2013-03-02 13:05:06

+0

表单是否包含帖子的“ID”?此外,由于您不更新帖子本身,您只需更新/插入收视表/模型中的数据 – thaJeztah 2013-03-02 13:05:55

+0

'rating_post'是所有收视率的总和。 'rating'是评分数量 @thaJeztah 是的,我通过postratings/view/id获取帖子的ID。 我想更新字段rating_post和评分中的表格文章,所以我可以列出评分最高的文章。因此,还需要更新帖子表 – 2013-03-02 13:13:48

回答

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
+0

我已经发布了添加方法。它仍然是一样的。在这种情况下,邮政将被保存,但邮政不会更新。 – 2013-03-02 13:58:21

+0

以上是执行此操作的正确方法之一。你不能仅仅将'$ this-> request-> data'放到'save()'而不考虑发生了什么 - 数据必须使用正确的键格式正确。发布'$ this-> request-> data'的转储。 – Ross 2013-03-02 14:08:10