If you need only one product attribute value in Magento 2, you do not always need to load the entire product through a repository or collection. That can be wasteful in loops, cron jobs and imports.
Using the Product Resource Model, you can read an attribute directly by product ID, attribute code and store ID:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
use Magento\Catalog\Model\ResourceModel\Product as ProductResource; public function __construct( private ProductResource $productResource ) { } public function getValue(int $productId, int $storeId): mixed { return $this->productResource->getAttributeRawValue( $productId, 'manufacturer', $storeId ); } |
Magento does not load the entire product with all its attributes. Instead, it reads only the value you need. This can be useful when processing many products but retrieving only one attribute for each.
For a dropdown attribute such as manufacturer gibt getAttributeRawValue() , however, Magento returns the stored option ID rather than the visible label. To retrieve the label, resolve the option through the attribute’s source:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
use Magento\Catalog\Model\ResourceModel\Product as ProductResource; use Magento\Eav\Model\Config as EavConfig; public function __construct( private ProductResource $productResource, private EavConfig $eavConfig ) { } public function getManufacturerLabel( int $productId, int $storeId ): ?string { $optionId = $this->productResource->getAttributeRawValue( $productId, 'manufacturer', $storeId ); if (!$optionId) { return null; } $attribute = $this->eavConfig->getAttribute( 'catalog_product', 'manufacturer' ); $attribute->setStoreId($storeId); return $attribute->getSource()->getOptionText($optionId); } |
A stored option ID such as 42 can then become the visible label Bosch. The store ID also allows different attribute values and option labels for different store views.