CakePHP的文章分类的功能实现

前些天实现了【微个人.大家园】的文章文类功能。现在回忆一下,是如何完成的吧。

具体的操作步骤如下:

1.在文章posts表里添加一个列,category_id。

2.在数据库中添加一个数据表,categories。

categories结构暂时包括两个字段,分别是id和category_name

3.然后要去建立一个Model去对应这个categories表。在/app/Model/下面建立文件Category.php 内容如下:

 1 <?php
 2 class Category extends AppModel {
 3     public $validate = array(
 4         'categorie_name' => array(
 5             'rule' => 'notEmpty'
 6         ),
 7         'id'=> array(
 8             'rule' => 'notEmpty'
 9         )
10     );
11      public $hasMany = 'Post';  //这里$hasMany表示每个分类模型里会包含许多文章,这样在获取一个分类模型的时候,就会同时获取对应的那些文章     
12 }

4.有了模型,接下来我们就可以建立Category模型对应的控制器。在/app/Controller/下面建立文件CategoriesController 内容如下:

 1 <?php
 2 class CategoriesController extends AppController {
 3     public $helpers = array('Html', 'Form');
 4     public $components = array('Session');
 5 
 6     public function index() {
 8         return $this->Category->find('all');
      //为了在博客的首页,显示出所有的分类,我们可以在视图文件中加入$categories = $this->requestAction('/categories/index');
      //去获取所有的分类模型对象
9 } 10 11 public function view($id) { 12 $this->Category->id = $id; 15 $this->set('category', $this->Category->read()); 17 } 19 }

5.现在可以去建立view视图了。在/app/View/Categories/下面建立视图文件view.ctp 

  在这个view.ctp中循环遍历分类模型中的文章,并显示,主要代码如下:

  

 1 <?php
 2                 for($i = 0; $i < $category['Category']['post_count']; $i++)  
 3                     {                
 4                      echo $this->Html->div('entrylistItem', $this->Html->div('entrylistPosttitle',$this->Html->link($category['Post'][$i]['title'], array('controller' => 'posts', 'action' => 'view', $category['Post'][$i]['id']),array('class' => 'entrylistItemTitle'))));
 5                      echo $this->Html->div('entrylistPostSummary',$this->Html->div('c_b_p_desc','摘要:'.utf8Substr(strip_tags($category['Post'][$i]['body']),0,250).'...'.$this->Html->link(' 阅读全文', array('controller' => 'posts', 'action' => 'view', $category['Post'][$i]['id']),array('class' => 'c_b_p_desc_readmore'))));
 6                      echo '<div class="entrylistItemPostDesc">posted @ <a title="permalink">'.$category['Post'][$i]['created'].'</a> 阮佳佳 阅读(6) | <a>评论 (0)</a>'.
 7                      $this->Html->link(' 编辑',array('controller' => 'posts', 'action' => 'edit', $category['Post'][$i]['id']),array('rel' => 'nofollow')).
 8                      '</div>';
 9                      }
10                  ?>
View Code

 

 

转载于:https://www.cnblogs.com/victorruan/p/3570991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值