Reading list Switch to dark mode

    Mysql operations in Magento 2 collection

    Updated 26 March 2024

    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.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    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