【发布时间】:2013-03-02 12:59:14
【问题描述】:
我有两个与此事相关的表格,posts 和 postratings。模型有如下关系:
Post hasmany PostratingPostrating 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));
}
【问题讨论】:
-
rating_post和ratings是什么? -
表单是否包含帖子的“id”?此外,由于您不更新帖子本身,您只需在评级表/模型中更新/插入数据
-
'rating_post' 是所有评分的总和。 'ratings' 是评级数量@thaJeztah 是的,我通过 postratings/view/id 获取帖子的 ID。我想更新 rating_post 和 rating 字段中的表帖子,以便列出评分最高的帖子。所以更新帖子表也是必要的
-
但是这些字段不是由用户输入的,也不是表单数据的一部分。看看@Ross 的答案,因为这是应该做的。发布评级的用户应该不能直接编辑帖子本身_中的数据,只能发布评级。您的应用程序逻辑应随后更新计算的总评分
-
@thaJeztah 帖子的字段对用户隐藏。它们填充了帖子表中帖子条目的值。
标签: cakephp saving-data cakephp-2.3