0

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?

3

Try with below code,

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

$collection->getSelect()->group('posts_id')->order('id DESC');
  • 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.