Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Mysql operations in Magento 2 collection

Mysql operations in Magento 2 collection like COUNT, GROUP BY and HAVING clause

Today we will see how to use Mysql operations in Magento 2 collection like COUNT, GROUP BY, and HAVING clause.

$collection->getSelect()->columns(['count' => new \Zend_Db_Expr('COUNT(badge)')]);

This will display the COUNT of the attribute badge in the collection.

To apply GROUP BY for the attribute badge –

$collection->getSelect()
           ->columns(['count' => new \Zend_Db_Expr('COUNT(badge)')])
           ->group('badge');

Now if you have some conditions to apply using MySQL HAVING then,

$collection->getSelect()
           ->columns(['count' => new \Zend_Db_Expr('COUNT(badge)')])
           ->group('badge')
           ->having('count like ?', $condition);

where $condition is the condition that you need to apply.

Write custom mysql query in Magento2

However, the use of these might lead to PHPCS warnings.

That’s it.

Happy coding 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home