Magento – Magento 2 – How get extension attributes from product collection

extension-attributesmagento2product-collection

I need to get the product collection with all extension attributes, specifically I need then to get the stockItem object with $product->getExtensionAttributes()->getStockItem(). So I have created a function like this:

protected function getCollection(ProductInterface $product): Collection
{
    $collection = $this->productCollectionFactory->create();

    $collection
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('visibility', ['eq' => Visibility::VISIBILITY_BOTH])
        ->addAttributeToFilter('status', ['eq' => Status::STATUS_ENABLED])
        ->addFieldToFilter('entity_id', ['neq' => $product->getId()])
        ->setPageSize(5);

    return $collection;
}

then I get all items from collection with $collection->getItems(), but in the loop of getItems() the extension attributes are null, why and how can I get them?

protected function populateProductList(Collection $collection)
{
    $items = $collection->getItems();

    $products = array_map(function ($product): ProductInterface {
        $stockItem = $product->getExtensionAttributes()->getStockItem();
        var_dump($stockItem);die; // IS NULL

        return $product;
    }, $items);

    return $products;
}

If I get a Product from the get method of productRepository, that product has all extension attributes compiled, I don't want to use productRepository to get another time the products for "only" the extension attributes, I want to avoid another call for performance reasons.

Best Answer

Try using getData to get complete object Data

protected function populateProductList(Collection $collection)
{
    $items = $collection->getItems();

    $products = array_map(function ($product): ProductInterface {
        $stockItem = $product->getExtensionAttributes()->getStockItem()->getData();
        var_dump($stockItem);die; // IS NULL

        return $product;
    }, $items);

    return $products;
}
Related Topic