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?
Bookmark this question. Show activity on this post. $products = Mage::getModel('catalog/product') ->addAttributeToFilter('status', array('eq' => 1)); echo $products->getSelect()->__toString();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With