0

I am using \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class to fetch the product collection.

Magento version: 2.2.6

I am trying to fetch both enabled & disabled products with the following code

status > 0, as in Magento, Enabled = 1 and Disabled = 2

$collection = $this->productCollection
                   ->addAttributeToSelect('*')
                   ->addAttributeToFilter('status', array('gt' => 0));

When I print the product collection data:

echo '<pre>';
print_r($collection->getData());
echo '</pre>';

I get the following result:

Array
(
    [0] => Array
        (
            [entity_id] => 27
            [attribute_set_id] => 4
            [type_id] => virtual
            [sku] => my-product-905546
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2018-12-04 10:18:06
            [updated_at] => 2018-12-04 10:20:31        
        )

    [1] => Array
        (
            [entity_id] => 26
            [attribute_set_id] => 4
            [type_id] => virtual
            [sku] => test-123-897069
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2018-12-03 06:38:39
            [updated_at] => 2018-12-04 09:57:10
        )
)

In the above product result:

  • one of the product is disabled and out-of-stock (sku: my-product-905546)
  • the other product is enabled and in-stock (sku: test-123-897069)

When I loop through the product collection, it only prints the enabled product name.

foreach ($collection as $product) {
    echo $product->getSku();
    echo '<br>';
}

Result:

test-123-897069

Expected Result:

my-product-905546
test-123-897069

Why is this so?

Any solution to print the disabled/out-of-stock product inside the foreach loop (load both enabled and disabled products into the collection) please?

5
  • By default disbled products are not loaded into collection Commented Dec 4, 2018 at 12:07
  • @MilindSingh How to load disabled products into the collection? Commented Dec 4, 2018 at 12:59
  • Is it working for you? Commented Dec 4, 2018 at 14:50
  • 1
    magento.stackexchange.com/a/211354/59216 Commented Dec 4, 2018 at 19:02
  • 1
    @MilindSingh Thanks for the link. It solved the issue of displaying out-of-stock products. However, I am still not able to display disabled products. Commented Dec 5, 2018 at 8:59

1 Answer 1

0

Try to use this below code :

$collection->joinTable( 'cataloginventory/stock_item', 'product_id=entity_id', array("stock_status" => "is_in_stock") )
           ->addAttributeToFilter('status', array('eq' => 2 ) );
1

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.