2

I have followed Magento 2 use group by in collection

I need to run below query

SELECT * FROM my_table WHERE status= 'Enable' GROUP BY id ORDER BY id DESC 

In collection factory i have below code

$collection = $this->collectionFactory->create()
           ->addFieldToFilter('id', $id)
           ->addFieldToFilter('status', 'Enable')
           ->setGroupBy('posts_id') // I tried to use group() as well
           ->setOrder('id','desc');

How to set Group By on above collection?

1 Answer 1

9

Try with below code,

$collection = $this->collectionFactory->create()
           ->addFieldToFilter('id', $id)
           ->addFieldToFilter('status', 'Enable');

$collection->getSelect()->group('posts_id')->order('id DESC');
3
  • how can use count with group by clause .
    – HaFiz Umer
    Commented Jul 4, 2019 at 13:28
  • @rakesh i have create a custom product attribute "sample_attribute" with drop down value i want to add group by in product collection but this gives unknown column how can i add group by in product collection Commented Mar 11, 2021 at 14:08
  • @VinitKumar did got any solutions, i'm also facing same issue Commented Apr 27, 2021 at 10:11

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.