I am using a headless magento 2 approach for my store. I have made an API which accepts parameters like:
category_slug, sort_by, sort_order, page_size, current_page
and returns the products matching the criteria.
Now the issue I am facing is, I want the out of stock products to be pushed down at the end of the ENTIRE collection.
My code is below:
$categoryProducts = $productFactory->create() ->addAttributeToSelect('*') ->addCategoriesFilter(array('in' => $categoryList)) ->addAttributeToFilter('status',1) ->addAttributeToFilter('visibility',4) ->addAttributeToSort($sort_by, $sort_order) ->addAttributeToSort('is_in_stock', 'DESC') ->setPageSize($page_size) ->setCurPage($current_page) ->load();
is_in_stock is a custom attribute I created which automatically gets set to 0 or 1 (0 being out of stock and 1 being in-stock), whenever a change in stock is detected (did this using an observer, working fine).
Now, suppose I want to sort the collection on PRICE, in ASC order the collection I am getting after this would look something like:
In-stock items of 10$, Out of stock items of 10$, In-stock items of 15$, Out of stock items of 15$, in stock items of 20$, and so on...
But what I want is:
In-stock items of 10$, In-stock items of 15$, in stock items of 20$, Out of stock items of 10$, Out of stock items of 15$, and so on...
I feel it's something really small and stupid that I am missing. any help would be appreciated.