Jump to content

How to select parent category if sub category has listings?


Recommended Posts

Hi guys,

 

I have a sql query that selects categories as long as they are a parent and they have items published within it:

 

SELECT c.* FROM #__categories AS c WHERE (SELECT COUNT(catid) FROM #__items WHERE catid=c.id AND published=1) > 0 AND parentid=0 ORDER BY name ASC

 

However, I'm having difficulty combining the above query to also get subcategories that are within a parent category but only when the subcategory has items in it and not its parent.

 

I want to get these "empty" parents if they contain subcategories with items in them... possible?

 

Cheers, RJP1

Sure, this is what I did:

 

function getCategories()
{
	$db =& JFactory::getDBO();
	$query = 'SELECT DISTINCT c.parentid FROM #__vault as i,jos_vault_categories as c WHERE i.catid=c.id AND c.parentid>0 AND i.published=1';
	$db->setQuery( $query );
	$parentidswithchildren = $db->loadObjectList();

	if ($parentidswithchildren) {
	$cat_ids = array();

	foreach ( $parentidswithchildren AS $c ) {
		$cat_ids[] = $c->parentid;
	}
	$in = "c.id IN (".implode(',',$cat_ids).") OR ";
	} else {
	$in = null;
	}

	$query = "SELECT c.* FROM #__vault_categories AS c WHERE [b]$in[/b](SELECT COUNT(catid) FROM #__vault WHERE catid=c.id AND published=1) > 0 AND parentid=0";

	$db->setQuery( $query );
	$categories = $db->loadObjectList();

    return $categories;
    }

 

If there are children, it puts their id's into a comma separated list as $in.

 

Works well. What do you think?

 

RJP1

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.