2

I want to get product collection and subcategory using category id.

I am trying

$category =  2;
    $product = $this->productFactory->create()->getCollection();
    $product->addAttributeToSelect('*');
    $product->addAttributeToFilter('category_ids',$category);

But it gives error like this

Column not found: 1054 Champ 'e.category_ids' inconnu dans where clause,...

And how to get subcategory id from category id?

5

Please change like this and it will works.

$collection = $this->productFactory->create()
->getCollection()
->addAttributeToSelect('*')
->addCategoriesFilter(['eq' => 2]);
  • 1
    Working fine, resulting as expected – Nalin Savaliya Sep 21 '16 at 12:23
4

You cannot add a category filter like that because category_id is not an attribute of the product.

The collection object (Magento\Catalog\Model\ResourceModel\Product\Collection) though does come with two handy functions to aid in this.

addCategoryFilter(\Magento\Catalog\Model\Category $category)

and

addCategoriesFilter(array $categoriesFilter)

In your case the later is probably more suitable so your code may look something like;

$collection = $this->productFactory->create()
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addCategoriesFilter(['eq' => 2]);
  • The above example with addCategoriesFilter does not work. You need to add an condition type like eq for Equal to, or neq for not equal to. In above example, change ->addCategoriesFilter([2]); to ->addCategoriesFilter([‘eq’ => 2]); and it should work. – Dennis van Schaik Jun 8 '16 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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