自己在做酒店管理的时候,直接做成无限极,顺便将代码分享出来
//酒店和房型信息列表
public function index(){
$Hotel=M('Hotel');
$hotelList=$Hotel->field('id,name,pid,path,concat(path,"-",id) as bpath ,sort')->order('sort desc,bpath')->select();
foreach ($hotelList as $k=>$v){
$hotelList[$k]['count']=intval(count(explode('-',$v['path']))-1); // 判断无限极层次深度
}
if($hotelList){
$this->hotelList=$hotelList;
}
$this->display();
}
//添加酒店/房型
public function add(){
if(IS_POST){ //post方法提交
if($_POST['name']==''){
$this->success('名称不能为空!');die;
}
$Hotel=M('Hotel');
if(intval($_POST['pid']) > 0){
$_POST['pid']=$_POST['pid'];
$parent=$Hotel->where(array('id'=>$this->_post('pid')))->find();
$_POST['path']=$parent['path'].'-'.$_POST['pid'];
}
$_POST['time']=time();
$data=getPost($_POST);//转义所有进入post方法的非法字符
$Hotel=M('Hotel');
if($Hotel->add($data)){
$this->success('保存成功!');
}else {
$this->error('保存失败!');die;
}
}else{
$this->error('非法请求');
}
}
数据库:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `yh_hotel`
-- ----------------------------
DROP TABLE IF EXISTS `yh_hotel`;
CREATE TABLE `yh_hotel` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(30) default '' COMMENT '酒店或者房型',
`sort` int(11) unsigned default '0' COMMENT '排序',
`path` varchar(50) default '0',
`pid` int(11) unsigned default '0' COMMENT '父级id',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of yh_hotel
-- ----------------------------
INSERT INTO `yh_hotel` VALUES ('1', 'A', '0', '0', '0');
INSERT INTO `yh_hotel` VALUES ('2', 'B', '0', '0', '0');
INSERT INTO `yh_hotel` VALUES ('3', 'A-1', '0', '0-1', '1');
INSERT INTO `yh_hotel` VALUES ('4', 'A-2', '0', '0-1', '1');
INSERT INTO `yh_hotel` VALUES ('5', 'B-1', '0', '0-2', '2');
INSERT INTO `yh_hotel` VALUES ('6', 'B-2', '0', '0-2', '2');
INSERT INTO `yh_hotel` VALUES ('7', 'B-1-1', '0', '0-2-5', '5');
INSERT INTO `yh_hotel` VALUES ('8', 'B-1-2', '0', '0-2-5', '5');