How to get out of stock product collection using object manager.
I retrieve product collection
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->addAttributeToSort('created_at', 'DESC')
->setPageSize(8)
->load();
but how to add out of stock condition to it.
I have tried this solution here but it does not work.
EDIT
Executing Below code gives following error:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollectionFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollection = $productCollectionFactory
->create()
->addAttributeToSelect('*')
->addAttributeToSort('created_at', 'DESC')
// use this if you want to filter by quantity = 0
->joinField('qty', 'cataloginventory_stock_item', 'product_id=entity_id', 'cataloginventory_stock_item.qty=0')
// use this if you want to filter by is_in_stock = false
->joinField('is_in_stock', 'cataloginventory_stock_item', 'product_id=entity_id', 'cataloginventory_stock_item.is_in_stock=0')
->setPageSize(8)
->load();
Error
PHP Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'at_qty.cataloginventory_stock_item.qty' in 'on clause' in D:\xa
mpp\htdocs\projects\magentoSite\vendor\magento\zendframework1\library\Zend\Db\State
ment\Pdo.php:228
Stack trace:
#0 D:\xampp\htdocs\projects\magentoSite\vendor\magento\zendframework1\library\Zend\
Db\Statement\Pdo.php(228): PDOStatement->execute(Array)
#1 D:\xampp\htdocs\projects\magentoSite\vendor\magento\framework\DB\Statement\Pdo\M
ysql.php(95): Zend_Db_Statement_Pdo->_execute(Array)
#2 D:\xampp\htdocs\projects\magentoSite\vendor\magento\zendframework1\library\Zend\
Db\Statement.php(303): Magento\Framework\DB\Statement\Pdo\Mysql->_execute(Array)
#3 D:\xampp\htdocs\projects\magentoSite\vendor\magento\zendframework1\library\Zend\
Db\Adapter\Abstract.php(480): Zend_Db_Statement->execute(Array)
#4 D:\xampp\htdocs\projects\magentoSite\vendor\magento\zendframework1\library\Zend\
Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT COUNT(
DI...', Array)
#5 D:\xampp\htdocs\proj in D:\xampp\htdocs\projects\magentoSite\vendor\magento\zend
framework1\library\Zend\Db\Statement\Pdo.php on line 235