分享一個用 ORM 寫無限極分類的帖子, 大佬請跳過.

ct4477xx_join發表於2020-04-10

實現無限極分類,運用場景為:樹目錄/部門分類/動態選單等

直接上程式碼:
模型:

 protected $table = 'menu';//自定義表名(protected $table)
    protected $primaryKey = 'id';//主鍵欄位,預設為id
    public $timestamps = false;//如果資料表中沒有created_at和updated_id欄位,則$timestamps則可以不設定,預設為true

    public function childrenModule()
    {
        return $this->hasMany(Menu::class,'fatherId','id');
    }

    public function children()
    {
        return $this->childrenModule()->with('children');
    }

控制層:

  $data = Menu::where(['fatherId' => 0, 'isDel' => 0])
            ->select('id', 'title', 'href', 'fontFamily', 'icon', 'spread', 'isCheck')
            ->with(['children:id,fatherId,title,href,fontFamily,icon,spread'])
            ->get();

最終實現效果:

{
    "id": 10,
    "title": "框架管理",
    "href": "sys/pages/frame/index",
    "fontFamily": "ok-icon",
    "icon": "",
    "spread": 0,
    "isCheck": 0,
    "children": [
        {
            "id": 11,
            "fatherId": 10,
            "title": "路由管理",
            "href": "",
            "fontFamily": "ok-icon",
            "icon": "&#xe6a3",
            "spread": 0,
            "children": [
                {
                    "id": 12,
                    "fatherId": 11,
                    "title": "路由管理1",
                    "href": null,
                    "fontFamily": "ok-icon",
                    "icon": "&#xe6a3",
                    "spread": 0,
                    "isCheck": 0,
                    "isDel": 1,
                    "children": []
                },
                {
                    "id": 13,
                    "fatherId": 11,
                    "title": "路由管理2",
                    "href": null,
                    "fontFamily": "ok-icon",
                    "icon": "&#xe6a3",
                    "spread": 0,
                    "isCheck": 0,
                    "isDel": 1,
                    "children": []
                }
            ]
        }
    ]
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章