Magento – Magento 2: addAttributeToFilter not returning any results

eavmagento2product-collection

When I use addAttributeToFilter on Magento\Catalog\Model\ResourceModel\Product\CollectionFactory, with a custom attribute, I always get 0 results.

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Api\SearchCriteriaBuilder;

...

$collection = $this->productCollection->create()
            ->addAttributeToSelect(array('custom_attribute','sku'))
            ->addAttributeToFilter('custom_attribute',['lt' => 1]);
        }

echo count($collection); //Returns 0

I also tried to use the search criteria object as Konrad Siamro sugested:

$search_criteria = $this->searchCriteriaBuilder
                ->addFilter('custom_attribute', 1, 'lt')
                ->create();
            $collection = $this->productRepository->getList($search_criteria);

echo $collection->getTotalCount(); //returns 0

But the results are the same. It works fine if I filter on a SKU, but my custom attribute returns nothing. I also tried adding the attribute to the flat product database and re indexing.

Update: Added code I used to create the attribute:

$eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'custom_attribute',
        [
            'type' => 'int',
            'backend' => '',
            'frontend' => '',
            'frontend_class' => 'validate-digits',
            'label' => 'Custom Attribute',
            'input' => 'text',
            'class' => 'class',
            'source' => '',
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => false,
            'user_defined' => false,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => true,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => ''
        ]
    );

Best Answer

Use search criteria for filtering collections.
Go to http://alanstorm.com/magento_2_understanding_object_repositories/
and look for search criteria.

Related Topic