2016-08-10 37 views
0

我對此很陌生,因此對任何愚蠢的錯誤表示歉意。我希望在用戶索引頁面有一列顯示每個用戶創建了多少帖子。該列在那裏,但我試圖找出如何讓用戶發佈帖子時自動更新。Cakephp顯示no。每個用戶發表的帖子

用戶/ index.ctp

<table> 
    <tr> 
     <th>Users</th> 
     <th>Account type</th> 
     <th>Registered</th> 
     <th>No. of posts</th> 
    </tr> 

    <?php foreach ($users as $user): ?> 
    <tr> 
     <td><?php echo $user['User']['username']; ?></td> 
     <td><?php echo $user['User']['role']; ?></td> 
     <td><?php echo $user['User']['created']; ?></td> 
     <td><?php echo $user['User']['post_count']; ?></td> 
    </tr> 
    <?php endforeach; ?> 
</table> 

在我的數據庫用戶表中的默認「POST_COUNT」爲0

所以在我的帖子控制器,我想一個部件添加到add()函數,其中post用戶post_count增加1。add()函數在PostsController.php

public function add() { 
    if ($this->request->is('post')) { 
     $this->request->data['Post']['user_id'] = $this->Auth->user('id'); 
     $this->request->data['Post']['user_username'] = $this->Auth->user('username'); 
     $this->Post->create(); 
     if ($this->Post->save($this->request->data)) { 
      $this->Flash->success(__('Your post has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } 
     $this->Flash->error(__('Unable to add your post.')); 
    } 
} 

我嘗試添加以下行:

public function add() { 
    if ($this->request->is('post')) { 
     $this->request->data['Post']['user_id'] = $this->Auth->user('id'); 
     $this->request->data['Post']['user_username'] = $this->Auth->user('username'); 
     $this->Post->create(); 
     if ($this->Post->save($this->request->data)) { 
      $this->Flash->success(__('Your post has been saved.')); 
     --> $postCount = $this->Auth->user('post_count'); 
     --> $postCount++; 
     --> $user['post_count'] = $postcount; 
      return $this->redirect(array('action' => 'index')); 
     } 
     $this->Flash->error(__('Unable to add your post.')); 
    } 
} 

,但他們都沒有效果。 任何幫助,將不勝感激,即使只是告訴我,如果我在正確的軌道上或沒有。

回答

0

好,遞增或用戶表decrimenting員額數是錯誤的做法。解決此問題的最佳方法是在用戶&後期模型中定義hasMany & belongsTo關係。一旦這種關係適合於外鍵。在用戶索引頁面中,您將獲得屬於每個用戶的帖子數量。

注意:爲了讓用戶

+0

啊我看到了,那麼我需要定義「用戶hasMany帖子」和「發佈belongsTo用戶」關係?或者只有「發佈所屬用戶」就足夠了? –

0

任何人誰在未來也有類似的問題,我創造的職位數目,我使用counterCache功能解決了這個。

我在模型寫道:

public $belongsTo = array(
    'User' => array(
     'counterCache' => true, 
    ) 
); 
相關問題