Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print collection mysql query in magento

Let's say I have a collection like:

$products = Mage::getModel('catalog/product')
            ->getCollection()
            ...
            ->load();

How do I print the actual MySQL code that gets executed?

like image 395
Luca Borrione Avatar asked Apr 04 '12 16:04

Luca Borrione


People also ask

How do I print a collection query in Magento 2?

Bookmark this question. Show activity on this post. $products = Mage::getModel('catalog/product') ->addAttributeToFilter('status', array('eq' => 1)); echo $products->getSelect()->__toString();

How do I run a direct SQL query in Magento 2?

You need to use the $this->resourceConnection object to run any Direct SQL Query. Reading From The Database All the records, fetchAll() => This method Fetches all SQL result rows as a sequential array. This method takes a query as it's the first parameter, executes it, and then returns all of the results as an array.


1 Answers

Most other answers here say that $products->getSelect() will do it - this is fine if all you're going to do with it is echo, but in fact getSelect() doesn't just return a string, it returns a Varien_Db_Select object.

Invoking echo on that object automatically triggers its __toString() method, so you just get the SQL string, but try passing it to Mage::log() and you'll get a lot more than you expected.

If you just want to log the SQL, you can use:

Mage::log($products->getSelect()->__toString());

Or how about using the object's own:

$products->printLogQuery(false, true); // don't echo, do log

printLogQuery is defined in lib/Varien/Data/Collection/Db.php.

like image 182
Doug McLean Avatar answered Nov 16 '22 04:11

Doug McLean