Magento 2中如何通过特定属性获取产品

How to get products by specific attributes in Magento 2

我有这个查询:

我在这里寻找传递 $product_id 变量的产品。

$product_id = 2047;
$attr_color = 54;
$attr_size = 170;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);

我想获得与 attr_color 和 attr_size 变量匹配的特定产品变体。 ¿我该怎么做?

To get the specific product variation with the attr_color and attr_size you need to get first that attribute and then pass your attribute_id to that attribute.

试试下面的代码:

            $product_id = 2047;
            $attr_color = 54;

          $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
          $_product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
          $_product = $_product->getResource()->getAttribute('color');    

         if ($_product->usesSource()) {
           $_product = $_product->getSource()->getOptionText($attr_color);
        }
           return $_product;

同样,您也可以为 attribute_size 执行此操作。