Magento 2 Product Collection Filtering and Sorting

collection;magento2product-attributeproduct-collectionproduct-sorting

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?

Best Answer

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

Related Topic