Welcome Guest, Not a member yet? Register   Sign In
Categories & Subcategories
#1

[eluser]sunnyd[/eluser]
Hi I hope someone can help me here...

I have been looking to set up a Category > Subcategory system using CodeIgniter (Brilliant Framework btw). I have tried almost everything I can think of... I came across this piece of code while scouring the web

Code:
function fetch_categories()
    {
        /* $this->db->order_by('cat_name');
        $query = $this->db->get('shop_category');
        if ($query->num_rows > 1)
        {
            return $query->result_array();
        } */
        
        $data = array();
        $this->db->select('cat_id,cat_name,cat_parent_id');
        // $this->db->where('status', 'active');
        $this->db->orderby('cat_parent_id','asc');
        $this->db->orderby('cat_name','asc');
        $this->db->groupby('cat_parent_id,cat_id');
        $Q = $this->db->get('shop_category');
        if ($Q->num_rows() > 0){
        foreach ($Q->result() as $row){
            if ($row->cat_parent_id > 0){
                $data[0][$row->cat_parent_id]['children'][$row->cat_id] = $row->cat_name;
            
            }else{
                $data[0][$row->cat_id]['cat_name'] = $row->cat_name;
            }
        }
        }
        $Q->free_result();
        return $data;  
        
    }

Although, it looks like what I need, I cant seem to find a way of using the code to display my category and subcategory list.

Anyone have an idea of how I could use the above code?

Thanks
#2

[eluser]ping timeout[/eluser]
If you have 2 tabels: category (id => int 11 primary key; name=> varchar 250 unique)
subcategory (id => int 11 primary key; name => varchar 250; category_id => int 11)

You could use something like this:
Code:
$query = $this->db->query("SELECT * FROM `category`");
  if ($query->num_rows() > 0)
     {
        foreach ($query->result() as $row)
        {
           echo $row->name;
       $querys = $this->db->query("SELECT * FROM `subcategory` WHERE `category_id`=" . $row->id);
        if ($querys->num_rows() > 0)
        {        
                foreach ($querys->result() as $rows)
           {
              echo $rows->name;                      
           }
        }
        }
      }
#3

[eluser]sunnyd[/eluser]
Hi, the code I posted uses a single table hence the reference to the parentid. What I am looking for is since this code goes in the model, what do I need to add to the controller and the view in order to display my categories.

Many thanks
#4

[eluser]jedd[/eluser]
[quote author="sunnyd" date="1257137200"]Hi, the code I posted uses a single table hence the reference to the parentid. What I am looking for is since this code goes in the model, what do I need to add to the controller and the view in order to display my categories.[/quote]

Hi sunnyd.

I see two ways this can go - people ask you lots and lots of questions and you slowly, piece by piece, over a couple of days, reveal what you've got, where you're heading, what you know, etc - or you could just spill everything now and save a lot of time.

Posting a segment of code that you 'found on the Internet' and asking how it could be made to work for your system is a tad ambitious - mostly because you didn't describe your system at all, but also because you didn't describe what didn't work about the code, what things you'd tried to make it work, and so on. You say you've tried everything you can think of - but it's hard for us to know what is included in that set. If you describe what you've tried, we're better informed, and so can give you better answers, yes?

You describe your system as being Category->sub-category, but now it seems you might be working with >2 levels of hierarchy. Is that right? How do you define a category v. a sub-category? Perhaps you could describe your schema, and what you actually want to get as your output for a given set of input(s).
#5

[eluser]sunnyd[/eluser]
Ok... This is the scenario I am trying to achieve. Jedd you are right in assuming that I am working with >2 levels of hierarchy.

Basically, I am wanting something like this:

Cars
------ Used Cars
------ News Cars

Models
------ Rover
------ Aston Martin
------ Mercedes Benz

This is is my current table schema:

Code:
CREATE TABLE `shop_category` (
   `cat_id` int(10) unsigned not null auto_increment,
   `cat_parent_id` int(11) not null default '0',
   `cat_name` varchar(50) not null,
   `cat_description` varchar(200) not null,
   `cat_image` varchar(255) not null,
   PRIMARY KEY (`cat_id`),
   KEY `cat_parent_id` (`cat_parent_id`),
   KEY `cat_name` (`cat_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=11;

In my controller function, I am calling the model as so:

Code:
function categories()
    {
        $data['site_name'] = "Site Name";
        $data['title'] = "Products";
        $data['meta']       = array('description' => 'welcome to codeigniter',
                                    'keywords' => 'welcome, codeigniter, ci',
                                );
        $data['categories'] = $this->products_model->fetch_categories();
        $data['content'] = $this->load->view('categories', $data , TRUE);    
        $this->load->view($this->template , $data);
    }

In my view file, I have:

Code:
<h1>Categories</h1>
<p>&lt;?php echo anchor(base_url(). 'admin/shop/add-category', 'Add Category'); ?&gt;</p>
<p>&lt;?php echo $this->session->flashdata('message'); ?&gt;</p>
&lt;?php foreach ($categories as $cat) { ?&gt;
    <p>&lt;?php echo $cat->cat_name; ?&gt;</p>
&lt;?php } ?&gt;

When trying to list the categories, I get the following error:

A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/categories.php

Line Number: 5



When I dump the value of $categories, the result is as follows:

Code:
Array
(
    [0] => Array
        (
            [4] => Array
                (
                    [cat_name] => Books
                    [children] => Array
                        (
                            [8] => Autobiography
                            [7] => Fiction
                            [5] => Horror
                            [6] => Science Fiction
                        )

                )

            [1] => Array
                (
                    [cat_name] => Cars
                    [children] => Array
                        (
                            [3] => Luxury
                        )

                )

            [2] => Array
                (
                    [cat_name] => Manga
                )

        )

)


I am trying to setup up a drop down menu so that when a customer hovers over the main category, any subcategories will be displayed assuming there is any. But I am lost as to how write the view code to achieve the desired result. I hope I am making better sense...
#6

[eluser]Dyllon[/eluser]
[quote author="sunnyd" date="1257140223"]
In my view file, I have:

Code:
<h1>Categories</h1>
<p>&lt;?php echo anchor(base_url(). 'admin/shop/add-category', 'Add Category'); ?&gt;</p>
<p>&lt;?php echo $this->session->flashdata('message'); ?&gt;</p>
&lt;?php foreach ($categories as $cat) { ?&gt;
    <p>&lt;?php echo $cat->cat_name; ?&gt;</p>
&lt;?php } ?&gt;

When trying to list the categories, I get the following error:

A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/categories.php

Line Number: 5

[/quote]

Line 5 in your view, $cat is an array not an object.

Code:
<h1>Categories</h1>
<p>&lt;?php echo anchor(base_url(). 'admin/shop/add-category', 'Add Category'); ?&gt;</p>
<p>&lt;?php echo $this->session->flashdata('message'); ?&gt;</p>
&lt;?php foreach ($categories as $cat) { ?&gt;
    <p>&lt;?php echo $cat['cat_name']; ?&gt;</p>
&lt;?php } ?&gt;
#7

[eluser]jedd[/eluser]
I'm still not clear.

The example you provide (for cars) seems a bit skewy, as 'new' and 'used' are attributes of 'cars', just as the different models are. It's not clear how you model a Used Rover, for example.

Do you want all descendants of an item (or set of items) to come back from the model and (somehow) be presented on the view, or are you happy with a single parent/children arrangement, which the user then navigates up and down in?

If it's the latter, it's really easy - you just have a model function that returns children of a given entity, and another to return the parent (so the user can navigate 'up'). This really is very easy, so it seems unlikely that it's what you're having difficulty doing (as much as I wish it were your intent).

If it's the former it's way more complex, as you have to deal with an unknown depth of information, decide how you display all that data, and deal with possible circular references.

The array you showed seems to have some redundant levels in it - not sure if there are other things going on elsewhere in that array? Remember, your model is allowed/encouraged to massage the lumps of data it outputs such that they suit your view - rather than writing your view to suit your database layout.




Theme © iAndrew 2016 - Forum software by © MyBB