I want to display In stock products first and out of stock at end of the listing.

I have used below code in magento/module-catalog/Model

$collection->joinField('stk', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'qty>=0', 'left')->setOrder('stk','desc');

But I am getting the error:

1 exception(s):
Exception #0 (Magento\Framework\Exception\LocalizedException): A joined field with this alias is already declared.

How can I solve this issue?

1 Answer 1


Please never work in the magento folder. Have a look here, how to override models: magento2 how to override model file?

In your case i would write probably a plugin for getAttributeUsedForSortByArray() where you add is_in_stock.

  • I was working in Magento folder only for testing. I'll override this. Could you please help me to do this task? Commented Dec 26, 2017 at 4:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.