How to filter product collection by product attribute in magento 2 like we did in magento 1.x using addAttributeToFilter method
2 Answers
addAttributeToFilter()
should works like in M1
on an EAV
collection and addFieldToFilter()
on a Flat
Collection
-
I wnat to filter start_date and end_date attributes, how you do? Commented Mar 24, 2016 at 9:17
-
$collection->addAttributeToFilter( [ ['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')], ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')], ]– SavooCommented Feb 19, 2018 at 11:27
have to add below functions in your block file and call getProductCollection() function template file
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\CategoryRepository $categoryRepository,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->addAttributeToFilter(
[
['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')],
['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')],
]
);
return collection;
}
You can also used below code :
if($from != ''){
$from = date_create($from);
$from = date_format($from,"Y-m-d H:i:s");
$collection->addAttributeToFilter('created_at', array('from' => $from));
}
if($to != ''){
$to = date_create($to);
$to = date_format($to,"Y-m-d H:i:s");
$collection->addAttributeToFilter('created_at', array('to' => $to));
}