You can't directly get product collection based on an attribute that exists in the attribute set.
First of all, You need to get all attributes set and from them, you can get all attributes from the attribute set.
After that, you can get product collection using the attribute set. It will automatically return the product collection of that attribute.
Add this below code in your block
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\Helloworld\Block;
class CustProColl extends \Magento\Framework\View\Element\Template {
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $collectionFactory;
/**
* @var \Magento\Catalog\Model\Product\AttributeSet\Options
*/
protected $options;
/**
* @var \Magento\Eav\Api\AttributeManagementInterface
*/
protected $attributeManagement;
/**
* @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory
* @param \Magento\Catalog\Model\Product\AttributeSet\Options $options
* @param \Magento\Eav\Api\AttributeManagementInterface $attributeManagement
*/
public function __construct(
...
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
\Magento\Catalog\Model\Product\AttributeSet\Options $options,
\Magento\Eav\Api\AttributeManagementInterface $attributeManagement
...
) {
...
$this->collectionFactory = $collectionFactory;
$this->options = $options;
$this->attributeManagement = $attributeManagement;
...
}
public function getProductColl() {
$attributeSetArray = $this->options->toOptionArray();
$attrSetIds = [];
foreach ($attributeSetArray as $key => $value) {
$attributes = $this->attributeManagement->getAttributes(\Magento\Catalog\Model\Product::ENTITY, $value['value']); // Get all attribute using attribute set id.
foreach ($attributes as $attribute) {
if ($attribute->getAttributeId() == 93) { // 93 is your attribute id which you want to check that exist in attribute set.
$attrSetIds[] = $value['value'];
}
}
}
$collection = $this->collectionFactory->create();
$collection->addFieldToSelect('*');
$collection->addFieldToFilter('attribute_set_id', ['in' => $attrSetIds]); // Return collection based on attribute set ids. It means your attribute exist in product.
return $collection;
}
}
I hope it's helpful for you.