Well, a new product attribute that you may notice in Magento2 is quantity_and_stock_status.
SELECT * FROM eav_attribute WHERE attribute_code = 'quantity_and_stock_status';
Query Result:
If you load a product object as:
$product = $this->_productRepository->getById($productId);
var_dump($product->getData());
You will see the value of quantity_and_stock_status as an array of is_in_stock and qty.
You must be thinking from where the heck it came from? These values are supposed to be in the stock item object.
Let’s dig it out.
Try to load any product:
$product = $this->_productRepository->getById($productId);
Inspect the value of following using X-Debug
$product->getData('quantity_and_stock_status')
You will notice that the value of quantity_and_stock_status is 1 initially (i.e. the default value).
Once the product is loaded, afterLoad() method of attribute’s backend_model: Magento\Catalog\Model\Product\Attribute\Backend\Stock is executed.
# Class: \Magento\Catalog\Model\Product\Attribute\Backend\Stock
/**
* Set inventory data to custom attribute
*
* @param Product $object
* @return $this
*/
public function afterLoad($object)
{
$stockItem = $this->stockRegistry->getStockItem($object->getId(), $object->getStore()->getWebsiteId());
$object->setData(
$this->getAttribute()->getAttributeCode(),
['is_in_stock' => $stockItem->getIsInStock(), 'qty' => $stockItem->getQty()]
);
return parent::afterLoad($object);
}
From above you can see clearly that is_in_stock and qty value are being fed by the $stockItem object.
And hence scalar value becomes an array.
Now it’s no more mystery, right? Cool.
Now let’s comment on – “Why has Magento2 team introduced quantity_and_stock_status attribute?”