ThinkPHP利用数据库字段做栏目的无限分类
一直以来对cms后台的栏目管理不太理解,尤其是子栏目顶级栏目这种关系,通过网上的搜索与自己的摸索,实现方法如下(原理是利用数据库的path字段):
1、建立简单的栏目表:
CREATE TABLE `self_cd`( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR( 255 ) NOT NULL, `pid` INT UNSIGNED NOT NULL DEFAULT '0', `path` TEXT NOT NULL ) ENGINE = MYISAM ;
2、建立CdModel.class.php模型
class CdModel extends Model{ /* * 数据验证 */ protected $_validate = array( array('name','require','栏目名称不能为空',1), ); /* * 自动提交 */ protected $_auto = array( array('path','getPath',3,'callback'), ); function getPath(){ //获取父id $pid = $_POST['pid']; // $pm = $this->field('id,path')->getById($pid); $path = $pid !== 0 ? $pm['path'].'-'.$pm['id'] : 0; return $path; } }
3、建CdAction.class.php控制器
class CdAction extends CommonAction{ function index(){ } function add(){ $cd = new CdModel(); $list = $cd->field("id,name,pid,path,concat(path,'-',id) as bpath")->order('bpath,id')->select(); foreach($list as $key=>$val){ $list[$key]['margin'] = (strlen(str_replace('-','',$val['path']))-1)*5; } $this->assign('cdlist',$list); $this->display(); } function insert(){ $cd = new CdModel(); if($cd->create()){ if(false!==$cd->add()){ echo '栏目添加成功'; $this->redirect(__APP__.'/Cd/add'); }else{ echo '数据添加失败'.$cd->getDbError(); } }else{ echo '数据验证失败'.$cd->getError(); } } }
4、模板实现:
add.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>创建栏目</title> </head> <body> <form method="post" action="__URL__/insert"> 栏目名称:<input type="text" name="name" /> 父栏目名:<select name="pid"> <option value="0">添加顶级栏目</option> <volist name='cdlist' id='data'> <option style="margin-left:{$data['margin']}" value="{$data['id']}">|-{$data['name']}</option> </volist> </select> <input type="submit" value="添加" /> </form> </body> </html>
5、显示效果如下
If the copyright belongs to the longfei, please indicate the source!!!