Skip to main content

Magento 2 How to set group by in Collection query?

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?

Jackson
  • 10k
  • 31
  • 131
  • 217