0

I'm trying to get a list of products filtered by categories, get all products from categories "Tees" plus all products from "watch" for example. The code:

$ids = ['16', '6'];
$productCollection = $this->_productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$productCollection->addCategoriesFilter(array('in' => $ids));

return $productCollection;

This works correctly, but it returns all variations of my configurable products, and I want just the main product, how can I get it? Thanks in advance.

1 Answer 1

1

I found a way to get this, just applying a filter on visibility of products, I found the answer in this link. The code:

First, we have to inject \Magento\Catalog\Model\Product\Visibility:

public function __construct(
    \Magento\Catalog\Model\Product\Visibility $productVisibility,
)
{
     $this->productVisibility = $productVisibility;
}

And then in my select code:

$ids = ['16', '6'];
//$ids = ['16'];
$productCollection = $this->_productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$productCollection->addCategoriesFilter(array('in' => $ids));
$productCollection->setVisibility($this->productVisibility->getVisibleInSiteIds());
return $productCollection;

With this, I get only the head products of my configurable products.

1
  • The $productCollection->setVisibility(...) do all the magic.
    – lpFranz
    Commented Nov 21, 2017 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.