Magento 2 filtering product collection and sorting
-
02-01-2021 - |
题
Considering below I can display products with true value of my custom attribute in ascending order based on position. How can I have products with false right after these in ascending too?
if ($subject->getCurrentOrder() == 'CustomAttribute') {
$collection ->addAttributeToFilter('myCustomAtt',1)->setOrder('position', 'asc');
$collection->load();
}
Is there any way to append $collection ->addAttributeToFilter('myCustomAtt',0)->setOrder('position', 'asc');
at the end of the $collection
?
解决方案
You can sort it by give values
if ($subject->getCurrentOrder() == 'CustomAttribute') {
$values=array(1);
$collection->setOrder('position', 'asc');
$collection->getSelect()->order(new \Zend_Db_Expr('FIELD(myCustomAtt,' . implode(',', $values).')'));
$collection->load();
}
Check for detail
其他提示
In this case, you should use sorting instead of filtering.
The following code will sort by myCustomAtt first, then by position.
if ($subject->getCurrentOrder() == 'CustomAttribute') { $collection->addAttributeToSort('myCustomAtt','DESC')->addAttributeToSort('position','ASC');
$collection->load();
}
It will work for you.
$collection->addAttributeToFilter('myCustomAtt', array('eq' => array(1,0)))->setOrder('position', 'asc');
$collection->load();