CakePHP如何检索所有类别及其各自的文章和文章显示::索引

时间:2011-06-11 12:42:17

标签: cakephp

我想检索所有类别的列表及其相应的帖子(限制10),并将其显示在我的文章控制器的索引操作/视图中。我已经设置了文章和类别控制器。

我希望在页面底部有类似于CNN.com的内容。

最好的方法是什么? 你能提供一些代码示例吗?

非常感谢,

Andre S。

2 个答案:

答案 0 :(得分:2)

您可以使用(缓存)元素和请求操作;因为类别不太可能改变那么多。

// views/elements/categories.ctp 
$categories= $this->requestAction('/categories/get_categories');
echo '<ul>';
foreach($categories as $category) {
    echo '<li>' . $category['Category']['name'] . '</li>';
}
echo '</ul>';


// in your layout
echo $this->element('categories', array('cache' => '+1 hour'));

上面的例子需要调整;但你应该明白这个想法。您可以使用请求操作访问您喜欢的任何数据;但它可能会导致性能不佳 - 因此建议使用缓存。

有关详细信息,请参阅the docs

答案 1 :(得分:2)

这就是我能够解决这个问题的方法。如果有人有最好的方法,请告诉我。谢谢!

这是我的文章

的Index.ctp查看文件
<div id="bottom_section" class="article_bottom_section">
<?php
    foreach ($categories as $category){
?>
<div>
    <div>
        <?php echo $category['Category']['title'];?>
    </div>
    <div>
        <?php
            echo $this->element(
                'category_relatedarticles',
            array(
            'categoryID' => $category['Category']['id']
            )
        );
        ?>
    </div>
</div>
<?php
    }
?>
</div>

然后是我的文章控制器中的索引操作

  $categories = $this->Article->Category->find(
            'all',
            array(
                'fields' => array(
                    'Category.id',
                    'Category.title'
                ),
                'order' => 'Category.id DESC',
                'recursive' => 1
            )
        );

    $this->set('categories');

这是我用来检索相应文章的元素

<div>
    <?php
    $RelatedArticles = $this->requestAction('/categories/getRelatedArticles/'.$categoryID);
    ?>
    <ul>
        <?php
        foreach($RelatedArticles as $RelatedArticle){
        ?>
        <li>
            <?php echo $RelatedArticle['Article']['title']; ?>
        </li>
        <?php
        }
        ?>
    </ul>
</div>

这是我的类别控制器中的getRelatedArticles函数

function getRelatedArticles($id = null){    

        $RelatedArticles = $this->Category->Article->find(
            'all',
            array(
                'fields' => array(
                    'Article.title',
                    'Article.id'
                ),
                'conditions' => array(
                    'Article.category_id =' => $id,
                ),
                'limit' => 6,
                'order' => 'Article.id DESC'            
            )
        );
        if (!empty($this->params['requested'])) {
            return $RelatedArticles;
        }else{
            $this->set('RelatedArticles');
        }
    }

它的效果非常好......如果有人知道更好更快的方式,请告诉我..谢谢