模型代码
public static function joinColumnChannel($parentId = 0) { // 使用模型自身的查询构造器 $categories = self::alias('a') // 为user表设置别名u ->join('channel c', 'a.channel_id = c.cid', 'LEFT') // LEFT JOIN channel表,并设置别名c ->field('a.typeid, a.typename, a.typeurl, a.channel_id, a.sort, a.fathorid, c.cname') // 指定查询的字段 ->where('a.isdel',0) ->where('a.fathorid',$parentId) ->order('a.sort asc') ->select(); // 执行查询,返回结果集 $tree = []; foreach ($categories as &$category) { $category['children'] = self::joinColumnChannel($category['typeid']); // 递归查询子栏目 if (empty($category['children'])) { unset($category['children']); // 如果没有子栏目,则移除children键 } $tree[] = $category->toArray(); // 转换为数组,避免视图层处理对象 } return $tree; }
控制器代码
// 栏目默认首页 列表 public function index() { // 实例化模型 $categoryTree = columnModel::joinColumnChannel(); // 调用模型方法获取整个分类树 $this->assign('result', $categoryTree); // 将分类树传递给视图 return $this->fetch('column/list'); }
视图页面代码
<ul> {volist name="result" id="category"} <li>{$category.typename} {notempty name="category.children"} <ul> {volist name="category.children" id="child"} <li>{$child.typename} {$child.typeid} {notempty name="child.children"} <ul> {volist name="child.children" id="child"} <li>{$child.typename} {$child.typeid} {notempty name="child.children"} <ul> {volist name="child.children" id="sunzi"} <li>{$sunzi.typename} {$sunzi.typeid} {notempty name="sunzi.children"} <!-- 这里可以递归调用子视图或继续嵌套ul/li --> <!-- 注意修改id --> {/notempty} </li> {/volist} </ul> {/notempty} </li> {/volist} </ul> {/notempty} </li> {/volist} </ul> {/notempty} </li> {/volist} </ul>
技术QQ交流群:157711366
技术微信:liehuweb
写评论