简体   繁体   中英

How to sort items by parent category when item is assigned to subcategory

I am trying sort Items by Parent Category when item is assigned to subcategory.

Tables

sql.Categories id , title , parent_id

sql.Classifieds id , title , category_id

Code

public function getLatestClassifieldsByParentCategories()
    {
        $query = $this->db->query("SELECT * FROM categories WHERE parent_id = '0'");
        $result = $query->result();


        foreach ($result as $parent) 
        {   

            $return[$parent->id] = $parent;

            $parent_id = $parent->id;
            $query = $this->db->query("SELECT * FROM categories WHERE parent_id = '$parent_id'"); 

            foreach ($result as $category)
            {
                $return[$parent->id]->category = $category;
                $return[$parent->id]->classifields = $this->cflatest->getClassifieldsLastestByCategory($category->id);
            }      
        }

        return $return;
    }

I found another way to do this what works fine

为什么不运行此查询?

SELECT * FROM classifieds JOIN categories ON classifieds.category_id = categories.id ORDER BY categories.title ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM