我對此很陌生,因此對任何愚蠢的錯誤表示歉意。我希望在用戶索引頁面有一列顯示每個用戶創建了多少帖子。該列在那裏,但我試圖找出如何讓用戶發佈帖子時自動更新。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.'));
}
}
,但他們都沒有效果。 任何幫助,將不勝感激,即使只是告訴我,如果我在正確的軌道上或沒有。
謝謝!我會盡力實現這一點。 –