【问题标题】:CakePHP 2.3 - How to add and update two different tables simultaneouslyCakePHP 2.3 - 如何同时添加和更新两个不同的表
【发布时间】:2013-03-02 12:59:14
【问题描述】:

我有两个与此事相关的表格,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));

}

【问题讨论】:

  • rating_postratings 是什么?
  • 表单是否包含帖子的“id”?此外,由于您不更新帖子本身,您只需在评级表/模型中更新/插入数据
  • 'rating_post' 是所有评分的总和。 'ratings' 是评级数量@thaJeztah 是的,我通过 postratings/view/id 获取帖子的 ID。我想更新 rating_post 和 rating 字段中的表帖子,以便列出评分最高的帖子。所以更新帖子表也是必要的
  • 但是这些字段不是由用户输入的,也不是表单数据的一部分。看看@Ross 的答案,因为这是应该做的。发布评级的用户应该不能直接编辑帖子本身_中的数据,只能发布评级。您的应用程序逻辑应随后更新计算的总评分
  • @thaJeztah 帖子的字段对用户隐藏。它们填充了帖子表中帖子条目的值。

标签: cakephp saving-data cakephp-2.3


【解决方案1】:

你确定是同时的吗?假设您的 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) 更新帖子表

【讨论】:

  • 我已经发布了 add 方法。它仍然是一样的。在这种情况下,postrating 会被保存,但不会更新。
  • 以上是正确的方法之一。你不能只是过去$this->request->datasave() 而不考虑正在发生的事情 - 数据必须采用正确的格式和正确的键。发布$this->request->data 的转储。
猜你喜欢
  • 2014-01-29
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多