0

Can I retrieve a product using an attribute code and/or attribute value? No product ID, no product name, just an attribute code and value.

0

You should be able to use any product collection with addAttributeToFilter in your module model/block/controller/observer/etc. See the example below for a generic model. Replace myattribute with your attribute code and myvalue with the value.

<?php

namespace Vendor\Module\Model;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

class MyModel {

    protected $collectionFactory;

    public function __construct(
        CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;      
    }

    public function getProductsByAttributeValue() {

        // Build Product collection, get name + sku
        $collection = $this->collectionFactory->create();
        $collection->addAttributeToSelect(['name','sku','myattribute']);

        // Only get products matching my attribute value
        $collection->addAttributeToFilter('myattribute', 'myvalue');

        return $collection;
    }   
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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