Today we discuss Magento 2 addFieldToFilter. addFieldToFilter is a method that can be use to filter collections in Magento 2. That will be use in product collection, category collection, order collection customer collection and other collection too. addFieldToFilter is adding WHERE condition in Mysql question to get collection.
addFieldToFilter condition
There are many condition you can use with addFieldToFilter. Example of condition equal, not equal, like , not like, in, not in, null, not null, greater than , less than , greater than equal to and less than equal to.
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
) {
$this->_productCollectionFactory = $productFactory;
}
public function getProductCollection()
{
return $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addFieldToFilter('sku’,'test');
}
Equal: eq
Now we use equal to filter production collection.
$this->_productCollectionFactory->addFieldToFilter('status', 1); // Without using the operator
Not Equals – neq
Now we use not equal to filter production collection.
Like – like
Now we use Like to filter production collection.
Not Like – nlike
Now we use not like to filter production collection.
In – in
Now we use In to filter production collection.
Not In – nin
Now we use not In to filter production collection.
NULL – null
Now we use null to filter production collection.
Not NULL – notnull
Now we use not null to filter production collection.
Greater Than – gt
Now we use greater than to filter production collection.
Less Than – lt
Now we use less than to filter production collection.
Greater Than or Equals To- gteq
Now we use greater than to filter production collection.
Less Than or Equals To – lteq
Now we use less than equal to filter production collection.