Home > Blockchain >  Magento 2: Get Product, Sku and Manufacturer name from database
Magento 2: Get Product, Sku and Manufacturer name from database

Time:12-28

I use this query to get Product Name and Sku. I would to add "brand name" that is stored in Manufacturer attributes . Is it possible to expand this query to get manufacturer name by product?

SELECT nametable.value, 
       nametable.store_id, 
       m2_catalog_product_entity.sku 
FROM   `m2_catalog_product_entity_varchar` AS nametable 
       LEFT JOIN m2_catalog_product_entity 
              ON nametable.entity_id = m2_catalog_product_entity.entity_id 
WHERE  nametable.attribute_id = (SELECT attribute_id 
                                 FROM   `m2_eav_attribute` 
                                 WHERE  `entity_type_id` = 4 and store_id = 0
                                        AND `attribute_code` LIKE 'name');

CodePudding user response:

I would highly recommend leveraging Magento 2 product object for retrieving the information instead of building queries yourself.

Inside a php class you can retrieve it like this using factory method:

<?php
  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $product
    ) {
        $this->product = $product;
        parent::__construct($context);
    }

    public function getProduct($id)
    {
        $product = $this->product->create()->load($entity_id);
        $sku = $product->getSku(); // get SKU
        $name = $product->getName(); // get name
        $manufacturer = $product->getManufacturer(); // get manufacturer
    }
}

Or via Object Manager

$entity_id = "your product id";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($entity_id);
$sku = $product->getSku(); // get SKU
$name = $product->getName(); // get name
$manufacturer = $product->getManufacturer(); // get manufacturer

To retrieve any attribute you want, you can use

$attribute = $product->getData("attribute_code"); // get any attribute
  • Related