Magento 2: Run Custom SQL Query

This article shows how to write/run/execute custom SQL queries in Magento 2. We need to instantiate class Magento\Framework\App\ResourceConnection for this. You have to inject this resource class in your module’s Block/Model/Controller class constructor. After that, you can use that object to run custom sql queries. In this example, I will simply be using object manager … Read more

Magento: Adding OR and AND query condition to collection

Here is a quick tip to add OR query and AND query to collection object. I am implementing this on product collection. Getting product collection // PRODUCT COLLECTION $collection = Mage::getModel('catalog/product')->getCollection(); Adding AND query condition Filtering collection to select only those products whose sku is like ‘ch’ AND status is equal to 1 (i.e. enabled … Read more

Magento: Set Random Order in Collection using RAND()

Scenario: You have created a custom module. You have entered certain data in your database. You need to show the data randomly. Solution: In MySQL the rand() function helps the select query to fetch data randomly. In Magento, you can select random rows from MySQL table using Zend_Db_Expr(‘RAND()’). You have to create a new function … Read more