![]() |
How could I either combine this query or send these to the view correctly? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: How could I either combine this query or send these to the view correctly? (/showthread.php?tid=5451) |
How could I either combine this query or send these to the view correctly? - El Forum - 01-22-2008 [eluser]Shpigford[/eluser] I have a table named 'categories'. Each row has a field called 'parent'. If 'parent' is 0, it's a top-level category, if not...then it's a sub category. I'm having an issue ultimately querying that and then sending it to the view. It's obviously pretty easy to pull all the categories: Code: function getCategories() Then in my controller I set that with: Code: 'categories' => $this->categories->getCategories() Then in the view: Code: <?php foreach($categories as $category): ?> But what I ultimately want to pull of is having the top level categories display and then under each top level category have its subcategories listed: Category 1 --Category 1a --Category 1b Category 2 --Category 2a etc etc Any suggestions for pulling that off? How could I either combine this query or send these to the view correctly? - El Forum - 01-22-2008 [eluser]Armchair Samurai[/eluser] This makes the assumption that the parent column contains a number which refers to the id column. In the model: Code: $this->db->select('x.id, x.name, y.name AS parent'); In the view: Code: <?php How could I either combine this query or send these to the view correctly? - El Forum - 01-22-2008 [eluser]ekeretex[/eluser] In this case, I'd use recursion (a function calling itself). It gives you the advantage of being able to go to any level of subcategories with minimal effort. With your example, i'd do this in the model: Code: function getCategories() { In the controller, pass the array to a recursive function and build the html in there. This is one of the few times I've done html in the controller but I'd rather the function stays in the controller. Code: function show () { Hope that helps |