0

I have a categories table

CREATE TABLE categories (
name
clean_name
image
description
lft
rgt
)

I need to be able to query all products within a category, organized by sub-categories. In other words:

Products
-Electronics
--Portable
>>> Product 1
>>> Product 2
--TV
>>> Product 1
>>> Product 2
>>> Product 3

So I'd love to be able to loop over Electronics and display the products within their distinctive categories...

So far, all I've been able to do is use a raw query to return the categories, but all on one level, and no products.

Ideally, I'd love to use Eloquent to manage all of this...

dcolumbus
  • 9,596
  • 26
  • 100
  • 165

1 Answers1

1

Your questions not very clear about exactly what you have set up so far, but essentially you would want:

  • a categories table with an id and name
  • a products table with an id, a category_id and a name.

You then need a corresponding model for each:

//category model
Category extends Eloquent
{
    public function products()
    {
        return $this->hasMany('Product');
    }
}

//product model
Product extends Eloquent
{
    public function category()
    {
        return $this->BelongsTo('Category');
    }
}

You would then grab your categories with your products and perhaps use a nest loop like so:

$categories Category::with('Products')->get();
foreach($categories as $category)
{
    echo '<h2>'.$category->name.'</h2>'
    foreach($category->products as $product)
    {
        echo $product->name
    }
}

Hope this helps, if not, you'll need to post some more details about what you have so far

SwiftD
  • 5,769
  • 6
  • 43
  • 67