0

How can I filter a collection by both an attribute and by a tag?

I can filter a product collection by doing:

Mage::app()->setCurrentStore( $storeId );

$collection = Mage::getModel( 'catalog/product' );

/** @var Mage_Catalog_Model_Resource_Product_Collection $collection */
$collection = $product->getCollection();
$collection->addAttributeToSelect( '*' );

$collection->addAttributeToFilter( 'attribute_set_id', $attribute_set_id );

And I can get the tag ID by doing:

$tag = Mage::getModel('tag/tag')->loadByName($tag_name);

I've found that you can do like this to filter by tag:

$products = Mage::getResourceModel('tag/product_collection')
                    ->addAttributeToSelect( '*' ) //
                    ->addTagFilter($tag->getId()) //filter by the tag object
                    ->addStoreFilter(Mage::app()->getStore()->getId());

But I'd like to combine the first type of filter with the second, as to be able to filter both by attribute and optionally by tag.

1 Answer 1

1

Try this:

$collection is your product collection.

$collection->joinTable(
            array('tag_relation' => 'tag/relation'), 'product_id = entity_id',
            array('tag_relation_id' => 'tag_relation_id', 'tag_id' => 'tag_id'), null, 'inner'
        );
        $collection->joinTable(
            array('tag' => 'tag/tag'), 'tag_id = tag_id', array('tag_name' => 'name'), null, 'inner'
        );
        $collection->getSelect()->where("tag.name {$operator} (?)", $tagString);
        $collection->getSelect()->where("tag.status = ?", Mage_Tag_Model_Tag::STATUS_APPROVED);

In the code above $operator would be your usual SQL operators (<,>,=,!= etc) $tagString will be the value of the tag you are interested in linking.

I use this in my Dynamic Category Products extension to allow rules that bring in products based on tags.

2
  • Great. A pity magento ORM doesn't allow to do this directly, without having to write your own joins, but nice solution nonetheless.
    – yivi
    Commented Nov 27, 2015 at 12:49
  • You are the man! Commented Apr 5, 2020 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.