How to print Product collection mysql query in magento2
-
05-03-2021 - |
Question
In my product page Price sorting not works properly. So i need to know which field value consider for sorting ? the issue occurs in configurable products.How do I print the actual MySQL code that gets executed?
Solution
Let's say you have a product collection like this:
//$collection is instance of Magento\Catalog\Model\ResourceModel\Product\Collection
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter(
'status', array('eq' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
);
Then you can simple get sql query by this:
echo $collection->getSelect();
or
you can add this to the app/code/Magento/Catalog/view/frontend/templates/product/list.phtml
file: (File location would depend on your theme)
echo $_productCollection->getSelect();
OTHER TIPS
Try this type code that is example of how to print mysql query.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollections = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $productCollections->create();
$collections->addAttributeToSelect('*');
echo $collections->getSelect()->__toString();
?>
In a simple way, echo your collection with getSelect function.
Here it is
echo $collection->getSelect();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange