$websiteId = 0;
$stockId = 'stock_id';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
$currentCategoryId = $category->getId();

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
 
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$category = $categoryCollectionFactory->create()->load($currentCategoryId);
 
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
// $collection->setOrder('is_salable', 'DESC');
$collection->getSelect()->joinLeft(
                array('_inv' => $collection->getResource()->getTable('cataloginventory_stock_status')),
                "_inv.product_id = e.entity_id and _inv.website_id=$websiteId",
                array('stock_status')
            );
            $collection->addExpressionAttributeToSelect('in_stock', 'IFNULL(_inv.stock_status,0)', array());
            $collection->getSelect()->reset('order');
            $collection->getSelect()->order('in_stock DESC');
 
//foreach ($collection as $product) {
//   echo "<pre>"; print_r($product->getData());
//} exit;

Categories: Magento2

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *