首先 article表 文章表,有cate_id和 cate表的id对应
bick项目 cate部分Model:
<?php
namespace app\Admin\model;
use think\Model;
use think\Collection;
use app\Admin\model\Article as ArticleModel;
class Cate extends Model
{
//递归调用 --无限极分类 格式化
public static function catetree($pid = 0, &$res = [], $level = 0)
{
$data = self::where(['pid'=>$pid])->order('order asc')->select();
// $data = self::all(['pid'=>$pid]);
foreach ($data as $k=>$v){
$v['cate_name'] = str_repeat('● — — ',$level).$v['cate_name'];
$res[] = $v;
self::catetree($v['id'],$res,$level+1);
}
return $res;
}
// 获取当前id下所有的子分类
public static function getChildrenId($id,&$res = []){
$data = self::all(['pid'=>$id]);
foreach ($data as $k=>$v){
$res[] = $v['id'];
self::getChildrenId($v['id'],$res);
}
return $res;
}
// 获取当前id下所有的子分类的文章
public static function getArticleid($id,&$res = []){
$type = gettype($id);//没有子分类时类型是string,有子分类类型是array
if ($type == 'array'){
$data = ArticleModel::where("cate_id in (".implode(',',$id).")")->select();
}
elseif ($type == 'string'){
$data = ArticleModel::where(['cate_id'=>$id])->select();
}
else{
$data = '';
}
if ($data){
foreach ($data as $k=>$v){
$res[] = $v['id'];
}
}
return $res;
}
}
Controller:
<?php
namespace app\Admin\controller;
use think\Controller;
use think\Request;
use app\Admin\model\Cate as CateModel;
use app\Admin\model\Article as ArticleModel;
class Cate extends BaseController
{
public function delete($id)
{
//获取子分类的id (数组)
$childrenId = CateModel::getChildrenId($id);
//如果有子分类,则删除子分类
if ($childrenId){
$childrenId[] = (int)$id; //如果有子分类,把父分类的id加入子分类id数组中
$delArtId = CateModel::getArticleid($childrenId);//所有子分类本类的文章id
$delchild = CateModel::destroy($childrenId);//删除子栏目 ,由于里面有本分类,所以本分类也删除
$article = ArticleModel::destroy(function ($query) use($childrenId){ //删除栏目下的文章
$query->where("cate_id in (".implode(',',$childrenId).")");
});
}
else{
$delArtId = CateModel::getArticleid($id);//所有本分类本类的文章id
$article = ArticleModel::destroy($delArtId);
$del = CateModel::destroy($id);//删除本分类
}
foreach ($delArtId as $value){
$delImg = ArticleModel::field('image')->where(['id'=>$value])->find();//遍历得到的每个结果
if ($delImg['image']){
$address = ROOT_PATH.'public'.$delImg['image'];//完整的图片地址
if (file_exists($address)){
@unlink($address);
}
}
};
if (isset($delchild)){
$this->success('删除栏目及子栏目成功!','cate/list');
}
elseif ($del){
$this->success('删除栏目成功!','cate/list');
}else{
$this->error('删除栏目失败!','cate/list');
}
}
}