How to get disable products in product collection in magento2.2
-
28-12-2020 - |
Question
I am trying to get product collection with all enabled/disabled products. It works fine until I upgrade Magento to 2.2. Now It's not fetching disabled products in collection. Here is my code -
class Index extends \Magento\Framework\App\Action\Action
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Framework\ObjectManagerInterface $objectmanager,
) {
$this->_objectManager = $objectmanager;
parent::__construct($context);
$this->_productCollectionFactory = $productCollectionFactory;
}
public function execute()
{
$collection = $this->_productCollectionFactory->create()
->addAttributeToSelect('*')
->addAttributeToFilter('diamond_vendor', array('in'=>$vendor))
//->addAttributeToFilter('status', array('in'=>array(1,2)))
->addAttributeToFilter('entity_id', array('nin'=>$notin_ids))
->setPageSize($noOfProducts)
->load();
}
}
In this I also tried with -
$collection->getSelect()->where('stock_status_index.stock_status IN(1,0)');
But its not making any effect.
Plz help me in this.
thx.
Solution
In magento 2.2, I have also faced this problem and it looks like bug to me but still we can use a workaround of using 'getPart' & 'setPart' functions to alter the load query of collection.
Note: Make sure you are using it in your custom module and not changing any magento core functionality or code. Please try to use it as:
$collection = $this->_productCollectionFactory->create()
->addAttributeToSelect('*')
->addAttributeToFilter('diamond_vendor', array('in'=>$vendor))
->addAttributeToFilter('entity_id', array('nin'=>$notin_ids))
->setPageSize($noOfProducts)
->load();
// Patch to alter load and get disabled products too
$collection->clear();
$where = $collection->getSelect()->getPart('where');
foreach ($where as $key => $condition)
{
if(strpos($condition, 'stock_status_index.stock_status = 1') !== false){
$updatedWhere[] = 'AND (stock_status_index.stock_status IN (1,0))';
} else {
$updatedWhere[] = $condition;
}
}
$collection->getSelect()->setPart('where', $updatedWhere);
$collection->load();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange