2016-08-10 13 views
0

私はこれに慣れていないので、愚かな間違いがあれば謝ります。ユーザーインデックスページに、各ユーザーが投稿した投稿の数を表示する列を持っています。列はありますが、ユーザーが投稿を行うたびに自動的に更新される方法を理解しようとしています。Cakephpディスプレイ番号。各ユーザーが作成した投稿の数

ユーザー/ 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

で、私はパートを追加しますポストを作るユーザのpost_countが1だけインクリメントされるadd()関数。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

ああ、私は "User hasMany Posts"と "Post belongsTo User"の両方の関係を定義する必要がありますか?または、「Post belongsTo User」だけで十分でしょうか? –

0

によって作成された記事の数を取得するには、私はcounterCache機能を使用してこれを解決しました。

私はポストモデルに書いた:

public $belongsTo = array(
    'User' => array(
     'counterCache' => true, 
    ) 
); 
関連する問題