【问题标题】:Magento 2: Get Product, Sku and Manufacturer name from databaseMagento 2:从数据库中获取产品、Sku 和制造商名称
【发布时间】:2021-12-27 10:00:32
【问题描述】:

我使用此查询来获取产品名称和 Sku。 我想添加存储在制造商属性中的“品牌名称”。是否可以扩展此查询以按产品获取制造商名称?

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');

【问题讨论】:

    标签: sql database magento2 magento-2.3


    【解决方案1】:

    我强烈建议利用 Magento 2 产品对象来检索信息,而不是自己构建查询。

    在 php 类中,您可以使用工厂方法像这样检索它:

    <?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
        }
    }
    

    或通过对象管理器

    $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
    

    要检索您想要的任何属性,您可以使用

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

    【讨论】:

    • 谢谢,这项工作很好,但 $product->getManufacturer 会返回一个 ID 而不是制造商名称。我使用 $product->getAttributeText("manufacturer");检索制造商的名称。
    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多