<?php
/*
@author:luowen
@time:2013-08-18
@desc:thinkphp中实现无限级分类(比较简单的版本)
//数据库表实现
-- phpMyAdmin SQL Dump
-- version 3.5.6
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2013 年 08 月 18 日 10:19
-- 服务器版本: 5.6.0-m4
-- PHP 版本: 5.3.23
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `test`
--
-- --------------------------------------------------------
--
-- 表的结构 `category`
--
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`pid` int(11) NOT NULL,
`path` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
--
-- 转存表中的数据 `category`
--
INSERT INTO `category` (`id`, `name`, `pid`, `path`) VALUES
(1, '新闻', 0, '0'),
(2, '北京新闻', 1, '0-1'),
(3, '体育', 0, '0'),
(4, '上地新闻', 2, '0-1-2'),
(5, '七街新闻', 2, '0-1-2'),
(6, '圣达菲', 0, '0'),
(7, '圣达菲个', 5, '0-1-2-5'),
(8, '江西新闻', 2, '0-1-2'),
(9, '广州新闻', 1, '0-1'),
(10, '广州新闻', 1, '0-1');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
//indexAction.class.php
class IndexAction extends Action{
public function Index(){
$category = D('category');
//将无限级分类中的数据去除来,根据concat(path,'-',id) => 'bpath' 实现排序(很关键)
$list = $category->field(array('id','name','pid','path',"concat(path,'-',id)"=>'bpath'))->order('bpath')->select();
foreach ($list as $key => $val){
//根据排序的位置生成无限极列表的样式
for($i = 0; $i < count(explode('-',$list[$key]['bpath']))-2 ; $i++){
$list[$key]['count'] .= "---";
}
}
$this->assign('list',$list);
$this->display();
}
public function add(){
$category = new CategoryModel();
if($category->create()){
if($category->add()){
$this->success('添加成功');
}
else{
$this->error('添加失败!');
}
}
else{
$this->error("error!");
//$category->getError();
}
}
}
/**
* 分类的模型类
* categoryModel.class.php
* 对应的表模型
*/
class CategoryModel extends Model{
protected $tableName = 'category';
protected $_auto = array(
//根据id生成无限极的父子关系
array('path','createPath',3,'callback'),
);
protected $_validate = array(
array('name','require','栏目必须填!'),
);
protected function createPath(){
$pid = isset($_POST['pid'])?$_POST['pid']:0;
$path = $this->field('path,id')->where("id = $pid")->find();
if(empty($path)){
return '0';
}
return $npath = $path['path'] . '-' . $path['id'];
}
}
