2013-03-02 42 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

相關問題