Filter collections in Magento or Magento 2 using addAttributeToFilter conditionals.
addFieldToFilter is adding WHERE condition in Mysql question to get the collection from the database, allowing to filter the collections like product collection, category collection, and many more by custom conditions. In a parallel manner, the integration of an advanced feature like the Multiselect Filter For Order Status in Magento 2 Order Grid takes this concept further.
Developing is all about if, when and else most of the time! (Developers, don’t get offended )
You may have to use conditions like 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.
However, using the addAttributeToFilter conditionals in Magento is effective when used with correct syntax. So, here’s the list!
Condition | Syntax | Example |
---|---|---|
Equals | eq | $category->addAttributeToFilter('status', array('eq' => 1)); |
Not Equals | neq | $category->addAttributeToFilter('name', array('neq' => 'test-category')); |
Like | like | $category->addAttributeToFilter('name', array('like' => 'UX%')); |
Not Like | nlike | $category->addAttributeToFilter('name', array('nlike' => 'err-cat%')); |
In | in | $category->addAttributeToFilter('id', array('in' => array(1,4,98)))); |
Not In | nin | $category->addAttributeToFilter('id', array('nin' => array(1,4,98)))); |
NULL | null | $category->addAttributeToFilter('description', array('null' => true)); |
Not NULL | notnull | $category->addAttributeToFilter('description', array('notnull' => true)); |
Greater Than | gt | $category->addAttributeToFilter('id', array('gt' => 5)); |
Less Than | lt | $category->addAttributeToFilter('id', array('lt' => 5)); |
Greater Than or Equals To | gteq | $category->addAttributeToFilter('id', array('gteq' => 5)); |
Less Than or Equals To | lteq | $category->addAttributeToFilter('id', array('lteq' => 5)); |
That’s it.
Feel free to share the post with fellow developers on social media.
Thank you.