2011-12-29 12 views
0

私はすべての記事でコメントを数えたいと思っていますが、foreachループ間のコメントカウンタは...正確にコメントを数えることはできません...だからループは必要ですがカウンタのループは必要ありませんforeachループでカウントを見つける方法は?

articles_controller.php

$count = $this->Article->Comment->find(
    'count', array('conditions' => array('Comment.status' => 1)) 
); 

記事/ index.ctp

<?php 
// initialise a counter for striping the table 
$count = 0; 

// loop through and display format 
foreach($articles as $article): 
    // stripes the table by adding a class to every other row 
    $class = (($count % 2) ? " class='altrow'": ''); 
    // increment count 
    $count++; 

?> 

<?php 
    echo $html->link(
     $article['Article']['title'], 
     array('action' => 'view', $article['Article']['id']) 
    ); 
?> 

<!-- date and comment counter --> 
<p class="entry-meta"> 
    <span class="date"><?php echo $article['Article']['created']; ?></span> <span class="meta-sep">|</span> 
    <span class="comments-link"> 
    <!-- here i will put the comment counter --> 
    <a href="declining-health.html#respond"> <?php echo $count ['Comment'];>Comments</a> 
    </span> 
</p> 

<?php endforeach; ?> 

答えて

2

はポスト>コメント関係でcounterCacheプロパティを使用して、ポストモデルでCOMMENT_COUNTフィールドを持っていることを確認してください。

IE:

<?php 
    class Post extends AppModel { 
     public $name = 'Post'; 
     public $hasMany = array(
      'Comment' => array(
       'className' => 'Comment', 
       'foreignKey' => 'post_id' 
      ) 
     ); 
    } 
?> 

<?php 
    class Comment extends AppModel { 
     public $name = 'Comment'; 
     public $belongsTo = array(
      'Post' => array(
       'className' => 'Comment', 
       'counterCache' => true 
      ) 
     ); 
    } 
?> 
// in the database table for table posts make sure to do the following 

add a column: comment_count int(11) default 0 

新しい投稿を追加するときに新しいコメントがカウント値が自動的にポストからなり追加または削除された場合さて、あなたは0の初期値とCOMMENT_COUNTフィールドを持っています更新。あなたはポストの配列をループとはCOMMENT_COUNTフィールドの値をエコーやコメントを確認するために値を使用するだけでできるようになります

は、その要素など

+0

abba thannnnnnks..moreありがとう..素晴らしいソリューション.. – user1080247

2

あなたはsizeof()と配列の要素数を数えることができます。

+0

を埋め込みます(idはこの<?phpのエコーはsizeofやる意味$ count ['Comment']);> – user1080247

+0

あなたは私を理解できません...カウントは、私はこのようなmysqlコードではないことを意味します。SELECT COUNT – user1080247

+0

何が問題なのですか?テーブル 'tbl'の行数を取得するには、 'SELECT COUNT(*)FROM tbl'を実行します。 – kba

0

クリスチャンは答えをくれましたが、フロントエンドですべてのスタイリングをお勧めします。

CSS擬似セレクター

//styles every second(even) elements 
.your_class:nth-child(2n){background-color:hotpink;} 

tr:nth-child(2n){background-color:hotpink;} 

...these also work with jquery 
関連する問題