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

How to set Group By on above collection?


Try with below code,

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

$collection->getSelect()->group('posts_id')->order('id DESC');
|improve this answer|||||
  • how can use count with group by clause . – HaFiz Umer Jul 4 '19 at 13:28

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.