Filtering Magento Product Collection by Category & Custom Attribute
As a developer working on a Magento API, you often need to retrieve specific product collections based on certain criteria such as category and custom attribute values. Let’s walk through how to achieve this efficiently.
Understanding the Magento Product Collection
In Magento, the Magento\Catalog\Model\ResourceModel\Product\Collection class is used to manage product data in a structured format. This collection allows you to filter, sort, and paginate products according to your business needs.
Fetching Products from a Specific Category
First, let’s fetch all the products belonging to a particular category.
$categoryId = 1; // Your desired category ID
$collection = $this->productCollectionFactory->create();
// Apply filters for the specified category
$this->_addFieldToFilter('category_id', array('eq' => $categoryId));
// Execute and return the collection
return $this->getData();
In this example, we create a new product collection and apply a field filter to include only products with the specific category_id (1 in this case). The _addFieldToFilter method is Magento’s built-in way of applying filters to collections.
Filtering by Custom Product Attribute
Now let’s add an additional layer of filtering based on a custom attribute, say ‘color’.
$attributeId = $this->eavConfig->getAttribute('catalog_product', 'color')->getId();
$colorValue = 'white'; // The desired color value
// Apply filter for the custom attribute
$collection->addFieldToFilter(
'attribute_id',
array('eq' => $attributeId)
)->joinAttribute(
'attribute',
'catalog_product_entity_int',
'entity_id = entity_id',
array(),
null,
'left'
);
$collection->getSelect()->where('attribute.value=?', $colorValue);
Here, we first get the ID of the color attribute using the eavConfig object. We then create a new join with the catalog_product_entity_int table to bring in the custom attribute data.
The addFieldToFilter method includes products based on the attribute’s ID, while the where clause further narrows down the selection by filtering for the specific color value (‘white’).
Putting it All Together
Combine both filters to get a collection of products that belong to category 1 and have ‘color’ set as ‘white’.
$categoryId = 1;
$attributeId = $this->eavConfig->getAttribute('catalog_product', 'color')->getId();
$colorValue = 'white';
$collection = $this->productCollectionFactory->create();
$this->_addFieldToFilter('category_id', array('eq' => $categoryId));
// Apply filter for the custom attribute
$collection->addFieldToFilter(
'attribute_id',
array('eq' => $attributeId)
)->joinAttribute(
'attribute',
'catalog_product_entity_int',
'entity_id = entity_id',
array(),
null,
'left'
);
$collection->getSelect()->where('attribute.value=?', $colorValue);
// Execute and return the collection
return $this->getData();
Best Practices for Product Collections
Remember to reset your collections after use, especially if they are being fetched multiple times in a script. You can do this with $collection->reset().
Also, consider using pagination or limiting the number of results returned by the query to optimize performance, especially when dealing with large product catalogs.
Conclusion
Filtering Magento product collections based on category and custom attribute values is a common requirement for building e-commerce APIs. By leveraging Magento’s built-in collection filtering methods (_addFieldToFilter and getSelect()->where), you can efficiently retrieve the desired products without writing complex SQL queries or dealing with raw database calls.
If you’re looking to dive deeper into Magento API development, consider exploring our comprehensive guides on LaravelCompany. We cover everything from setup and authentication to advanced topics like B2B APIs and integration with third-party systems.