按类别和子类别制作心愿单树

时间:2018-01-23 05:27:38

标签: php mysql codeigniter activerecord codeigniter-3

需要从wishlist添加类别树和子类别

我的控制器给出了回复。

public function index_get() {
    $this->check_authentication();
    $wishlist = $this->Wishlist_model->getByUserId($this->_user->id);
    $this->set_response([
        'status' => TRUE,
        'response' => $wishlist,
            ], REST_Controller::HTTP_OK);
}

我的模型将类别和子类别完美地提取为树,但如果我只将子类别添加到我的心愿单中,则它不会显示,因为其父类别不存在于心愿单表中。如何解决这个问题

public function getByUserId($id) {
    $categories = $this->getWishlistCategory($id,1,0); // userid/type/order
    $subCats = $this->getWishlistCategory($id,2,1);
    $this->mapCateogires($categories, $subCats);
    return $categories;
}

private function mapCateogires($categories, $subCats) {
    $data = array();
    foreach ($subCats as $item) {
        $data[$item->parentid][] = $item;
    }
    foreach ($categories as $item) {
        $item->childs = isset($data[$item->id]) ? $data[$item->id] : [];
    }
}
private function getWishlistCategory($userid, $type,$order) {
    $query = $this->db
            ->select("W.id as wishlishid, W.userid, W.type, W.itemid as id,W.created, C.name, C.icon, C.order,C.parentid,C.hasChild")
            ->from("wishlist as W")
            ->join("categories as C", "W.itemid=C.id",'LEFT')
            ->where("W.userid", $userid)
            ->where("W.type", $type)
            ->where("C.order", $order)
            ->get();
            return $query && $query->num_rows() ? $query->result() : [];

}

这是我的实际结果

{
"status": true,
"response": {
    "categories": [
        {
            "wishlishid": "20",
            "userid": "24",
            "type": "1",
            "id": "1",
            "created": "2018-01-22 12:32:47",
            "name": "Audio, Video, Electronics",
            "icon": null,
            "order": "0",
            "parentid": null,
            "hasChild": "1",
            "childs": [
                {
                    "wishlishid": "23",
                    "userid": "24",
                    "type": "2",
                    "id": "15",
                    "created": "2018-01-22 12:32:47",
                    "name": "Air Conditioners",
                    "icon": null,
                    "order": "1",
                    "parentid": "1",
                    "hasChild": "1"
                }

            ]
        },
        {
            "wishlishid": "21",
            "userid": "24",
            "type": "1",
            "id": "2",
            "created": "2018-01-22 12:32:47",
            "name": "Beauty, Health & Personal Care",
            "icon": null,
            "order": "0",
            "parentid": null,
            "hasChild": "1",
            "childs": []
        }
    ]
}
}

但是我已经在我的心愿单中添加了一个子类别,但未显示,因为它的父类别不在愿望清单项目中。如果愿望清单表中没有父类别从类别表中获取并将其显示为树。

我的愿望清单表格结构:

enter image description here

我的类别表格结构:

enter image description here

0 个答案:

没有答案