我有两个与此事相关的表,帖子和帖子。模型具有以下关系:
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的方法添加
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 :(得分: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);
}
E.g:
existing_rating + new_rating
)