Question

I'll explain the 'real life' application of this so it's easier to understand.

I'm working on an eCommerce app that has a category structure. It starts at the top level and gradually moves down through subcategories. For example Home > Electronics > TVs > Plasma

I'm using a single page for this, showing the 'home' page if no category is defined, the subcategories if there are any, and finally the products if there are no subcategories.

This all works fine, however when I get to the 2nd part - displaying subcategories, the page is a little empty. Therefore, I'd like to display a selection of products that span all of the subcategories applicable.

This is where I'm struggling - in most cases, there will be a few subcategories. However, I'm not sure how to structure the 'where' query using the results of the previous query (code snippets below for reference).

I don't believe QofQ would be worth exploring, and I've made a vain attempt at doing something with substrings, without success.

Any pointers much appreciated!

<cfquery name="getcategories">
SELECT p.ID AS CategoryID, p.Cat_Name as CategoryName, p.Cat_Shortname, c.ID AS SubCategoryID, c.Cat_Name as SubCategoryName, c.Cat_Shortname AS SubCatShortname
FROM    product_categories p LEFT JOIN product_categories c ON p.ID = c.SubcategoryOf
WHERE  p.SubcategoryOf = 0
</cfquery>

<cfif IsDefined('url.cat')>
<!--- Look for additional subcategories --->
<cfquery name="getsubcategories">
SELECT *
FROM product_categories
WHERE Subcategoryof='#url.cat#'
</cfquery>
<cfquery name="getproducts">
SELECT *
FROM products
WHERE categoryid='#url.cat#'
ORDER BY RAND()
</cfquery>
</cfif>
Was it helpful?

Solution

Assuming your products table contains a subcategoryID of some kind you can use the following to get a list of sub category IDs from the query getsubcategories:

<cfset subCategoryIDs = valueList(getsubcategories.subCategoryID) >

This will give you a list of all subCategoryIDs. You can the feed this into the getproducts query like so:

<cfquery name="getproducts">
SELECT *
FROM products
WHERE subCategoryID in (<cfqueryparam cfsqltype="cf_sql_integer" value="#subCategoryIDs#" list="true">)
ORDER BY RAND()
</cfquery>

You should always cfqueryparam your query parameters.

OTHER TIPS

If i understand your database structure, this query should return all products in all subcategories.

<cfquery name="getallproducts">
  SELECT *
  FROM products p LEFT JOIN product_categories pc ON p.categoryID = pc.ID
  WHERE pc.Subcategoryof= <cfqueryparam cfsqltype="cf_sql_integer" value="#url.cat#">
</cfquery>

note: you really do want to use cfqueryparam here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top