ThinkPHP5使用模型进行多级栏目输出并在视图页面遍历显示

模型代码

// application/common/model/Category.php  
namespace app\common\model;  
  
use think\Model;  
  
class Category extends Model  
{  
    // ... 其他模型属性和方法  
  
    /**  
     * 获取指定父ID下的所有子栏目,包括子栏目的子栏目等(递归)  
     * @param int $parentId 父栏目ID  
     * @return array 栏目数组  
     */  
    public static function getCategoryTree($parentId = 0)  
    {  
        $categories = self::where('parent_id', $parentId)->select();  
        $tree = [];  
        foreach ($categories as &$category) {  
            $category['children'] = self::getCategoryTree($category['id']); // 递归查询子栏目  
            if (empty($category['children'])) {  
                unset($category['children']); // 如果没有子栏目,则移除children键  
            }  
            $tree[] = $category->toArray(); // 转换为数组,避免视图层处理对象  
        }  
        return $tree;  
    }  
}

控制器代码

// application/index/controller/Category.php  
namespace app\index\controller;  
  
use think\Controller;  
use app\common\model\Category;  
  
class CategoryController extends Controller  
{  
    public function index()  
    {  
        $categoryTree = Category::getCategoryTree(); // 调用模型方法获取整个分类树  
        $this->assign('categoryTree', $categoryTree); // 将分类树传递给视图  
        return $this->fetch(); // 渲染视图  
    }  
}

视图代码

<!-- application/index/view/category/index.html -->  
<!DOCTYPE html>  
<html>  
<head>  
    <title>多级栏目</title>  
</head>  
<body>  
    <ul>  
        {volist name="categoryTree" id="category"}  
        <li>{$category.name}  
            {notempty name="category.children"}  
            <ul>  
                {volist name="category.children" id="child"}  
                <li>{$child.name}  
                    {notempty name="child.children"}  
                    <!-- 这里可以递归调用子视图或继续嵌套ul/li -->  
                    {/notempty}  
                </li>  
                {/volist}  
            </ul>  
            {/notempty}  
        </li>  
        {/volist}  
    </ul>  
</body>  
</html>

 

阅读剩余
THE END