數據表結構如下: 控制器核心代碼: <?php namespace app\index\controller; use think\Controller; class Goods extends Controller { public function product_category() { re ...
數據表結構如下:
控制器核心代碼:
<?php namespace app\index\controller; use think\Controller; class Goods extends Controller { public function product_category() { return $this->fetch(); } public function product_category_add() { $m = Model('goods_type'); // 根據paths進行排序 // \對,進行轉義,因為本身是作為分隔符使用 $data = $m->field("*,concat(path,'\,',id) as paths")->order('paths')->select(); foreach($data as $k=>$v){ //根據level的值,決定需要迴圈幾次,生成分割線 $v['name'] = str_repeat("|------", $v['level']).$v['name']; } $this->assign('data', $data); return $this->fetch(); } //添加分類 public function goods_type_add(){ if($_POST['name'] === ''){ echo '<script>alert("添加失敗,分類名不能為空");parent.location.href="product_category";</script>'; } //var_dump($_POST); $data['name'] = $_POST['name']; $data['pid'] = $_POST['pid']; $m = Model('goods_type'); if($data['pid'] === "0"){ //如果是一級分類 $data['level'] = 1; //新增分類的id $info = $m->where('1=1')->order('id desc')->find(); $newId = $info['id']+1; $data['path'] = '0,'.$newId; }else{ $pinfo = $m->field('path,level')->where('id',$data['pid'])->select(); //查找父分類的path和level $data['level'] = $pinfo[0]['level']+1; //新增分類的id $info = $m->where('1=1')->order('id desc')->find(); $newId = $info['id']+1; $data['path'] = $pinfo[0]['path'].','.$newId; } $res = $m->data($data)->save(); if($res){ echo '<script>alert("添加成功");parent.location.href="product_category";</script>'; }else{ echo '<script>alert("添加失敗");parent.location.href="product_category";</script>'; } } //獲取分類數據 public function product_category_ajax(){ $m = model('goods_type'); $data = $m->field('id,pid,name')->select(); echo json_encode($data); } //刪除分類數據 public function product_category_del(){ $id = $_GET['id']; $m = model('goods_type'); $res = $m->where('pid',$id)->find(); if($res){ $str = '該分類下還有子分類,不允許直接刪除'; echo json_encode($str); }else{ $result = $m->where('id',$id)->delete(); if($result){ echo 1; }else{ $str = '刪除失敗'; echo json_encode($str); } } } }
實現效果