How to print collection mysql query in magento - debugging

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?

You can always view your sql query at a certain point by echoing getSelect as shown:
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();
To change query parameters you want to check out methods like:
$products->addAttributeToSelect('someattribute');
$products->addAttributeToFilter('someattribute', array('eq'=>'1'));

You can print collection using below code:
We can print query of collection using getSelect()->__toString()
$products = Mage::getModel(‘catalog/product’)
->addAttributeToFilter(‘status’, array(‘eq’ => 1));
echo $products->getSelect()->__toString();
Have you seen http://kuldipchudasama.wordpress.com/2012/07/16/magento-print-query-of-collection/?
This works well.

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.

You can print
$products->getSelect()->assemble();

I work with collections every day. This is without a doubt the correct way.
echo $collection->getSelectSql(true);

If you simple set the first parameter of ->load() to true, like so:
$products = Mage::getModel('catalog/product')
->getCollection()
...
->load(true);

In Magento 2:-
namespace <Company>\<Module>\Block\Adminhtml\Tab\Log;
class Grid
extends \Magento\Backend\Block\Widget\Grid\Extended
{
protected $_collectionFactory;
/**
* Constructor
*
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Backend\Helper\Data $backendHelper
* #param \<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory
* #param Psr\Log\LoggerInterface $logger
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory,
\Psr\Log\LoggerInterface $logger,
array $data = []
) {
$this->_logger = $logger;
$this->_collectionFactory = $collectionFactory;
parent::__construct($context, $backendHelper, $data);
}
/**
* {#inheritdoc}
*/
protected function _prepareCollection()
{
$collection = $this->_collectionFactory->create();
$this->_logger->info($collection->getSelect()->__toString());
$this->setCollection($collection);
return parent::_prepareCollection();
}
}
And remember that the collection factory is a magic class that can attaches to every class as Magento 1 wasn't complicated enough.

Step 1-
$result_colletion = print_r($collection->getSelect());
Mage::log($$result_colletion, null, custom_collection.log,true);
Step 2-
After that Login into magento admin section and enable to log setting . Please see below .
System > Configuration > Developer > Log Settings
Step 3-
After that see the log file custom_collection.log in var/log/ folder .

Try following code.
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();

Related

Using event sales_order_place_after doesn't return custom product attributes in magento

I try to get the products which have been bought.
This is my code:
/** #var $order Mage_Sales_Model_Order */
$order = $eventObserver->getOrder();
/** #var $items Mage_Sales_Model_Resource_Order_Collection */
$items = $order->getItemsCollection(array(), TRUE);
/** #var $item Mage_Sales_Model_Order_Item */
foreach($items as $item) {
$product = $item->getProduct();
var_dump($product->getData('language'));
}
Language is a custom attribute. In this case it is empty, and I have no idea why. All default attributes, like name, id or sku are working.
This language is used as configurable attribute.
What have I to do, to get the value?
Try this:
$items = $order->getAllVisibleItems()
Got it!
When I take the product ID and load the product again:
$product = $item->getProduct();
$product = Mage::getModel('catalog/product')->load( $product->getId() );
I get the language as number.

Magento unique TaxVat atrribute for every customer

.Hi,
I'm trying to make the attribute taxvat unique for every customer. (especially for users that i create from the backend). i.e no duplicates.
Just like the email attribute, if the email is already used, user gets notified to use another email.
I tried from the eav_attribute to change "is_unique" to "1" but nothing happened..
Can you please help me how to achieve this..?
Thanks
ok, i found the solution..
Find file /app/code/core/Mage/Customer/Model/Form.php (Don't forget to override instead..)
in "public function validateData(array $data)"
add the code inside the
foreach ($this->getAttributes() as $attribute)
foreach ($this->getAttributes() as $attribute) {
...
...
//## code to add
if ($attribute->getIsUnique()) {
$cid = $this->getEntity()->getData('entity_id'); //get current customer id
$cli = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToFilter($attribute->getAttributeCode(), $data[$attribute->getAttributeCode()]);
//->addFieldToFilter('customer_id', array('neq' => $cid)); //exclude current user from results //###### not working......
$flag=0;
foreach ($cli as $customer) {
$dataid=$customer->getId();
if ($dataid != $cid) //if the value is from another customer_id
$flag |= 1; //we found a dup value
}
if ($flag) {
$label = $attribute->getStoreLabel();
$errors = array_merge($errors, Mage::helper('customer')->__('"%s" already used!',$label));
}
}
//## End of code to add
}
I've modified what Karpa wrote to make it better
if ($attribute->getIsUnique()) {
$cid = $this->getEntity()->getData('entity_id'); //get current customer id
$cli = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToFilter($attribute->getAttributeCode(), $data[$attribute->getAttributeCode()])
->addFieldToFilter('entity_id', array('neq' => $cid)); //exclude current user from results //###### not working......
if (count($cli)>0) {
$label = $attribute->getStoreLabel();
$errors = array_merge($errors, array(Mage::helper('customer')->__('"%s" already used!',$label)));
}
I was looking for this solution for some time. But I noticed that the form.php file that you reference is the 1.5 version of magento. In version 1.6 the file is different ... Where to put this code in version 1.6? Thank you.
I found the file. It is in /app/code/core/Mage/Eav/Model/form.php.
But I put the code and did not work here ... I keep trying a solution.
You can create an event :
<customer_save_before>
<observers>
<mymodule_customer_save_before>
<class>mymodule/observer</class>
<method>checkUniqueAttribute</method>
</mymodule_customer_save_before>
</observers>
</customer_save_before>
And in your observer :
/**
* Check customer attribute which must be unique
*
* #param Varien_Event_Observer $observer
* #return $this
* ##see customer_save_before
*/
public function checkUniqueAttribute(Varien_Event_Observer $observer)
{
/** #var Mage_Customer_Model_Customer $customer */
$customer = $observer->getEvent()->getCustomer();
foreach ($customer->getAttributes() as $attribute) {
if ($attribute->getIsUnique()) {
$collection = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToFilter($attribute->getAttributeCode(), $customer->getData($attribute->getAttributeCode()))
->addFieldToFilter('entity_id', array('neq' => $customer->getId()));
if ($collection->getSize()) {
Mage::throwException(sprintf(
'The value %s for %s is already used',
$customer->getData($attribute->getAttributeCode()),
$attribute->getStoreLabel()
));
}
}
}
return $this;

issue with obtaining "Default Store View" value for custom attribute in Magento?

I am using the below code to get attribute name
$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','pricee');
echo $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attribute->getFrontendLabel()
in this 'pricee' is the attribute code. But the output is not the desired one, instead the value under "Admin" is retrieved. Below screen shows the actual field i need to show
What am i doing wrong? Please suggest.
Mage::app()->setCurrentStore('default');
This will select the default store that you are after.
You can also try the getStoreLabel($storeId) function for more specific stuff.
This function is found at: /app/code/core/Mage/Eav/Model/Entity/Attribute.php and looks like this:
/**
* Return store label of attribute
*
* #return string
*/
public function getStoreLabel($storeId = null)
{
if ($this->hasData('store_label')) {
return $this->getData('store_label');
}
$store = Mage::app()->getStore($storeId);
$label = false;
if (!$store->isAdmin()) {
$labels = $this->getStoreLabels();
if (isset($labels[$store->getId()])) {
return $labels[$store->getId()];
}
}
return $this->getFrontendLabel();
}
HTH,
Shaun O'Reilly
Actually the below code worked in my case,
$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','ATTRIBUTE_CODE_HERE');
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();
echo $attribute->getStoreLabels();
The output of this is : Array
(
[1] => Price
)

In magento - same code for getting all categories running well with sorted in localhost but not in web server

I have got all categories sorted as in admin in localhost but in web server its coming without sorted. I tried same code and order in both localhost and web server.
That is really a pain.Please help me!
Here is my code:
$categories = Mage::helper('catalog/category');
$collection = $categories->getStoreCategories(false,true,false);
foreach($collection as $_category)
{
//Do something
echo $_category->getName();
}
In helper:
/**
* Retrieve current store categories
*
* #param boolean|string $sorted
* #param boolean $asCollection
* #return Varien_Data_Tree_Node_Collection|Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection|array
*/
public function getStoreCategories($sorted=false, $asCollection=false, $toLoad=true)
And your first parameter equals to false, means collection won't be sorted.
$collection = $categories->getStoreCategories(false,true,false);

Check whether a product is in the wishlist or not

I'm working on a Magento theme, and I need to build a function that can check to see whether or not a product has been added to the user's wishlist.
Magento has a "Mage_Wishlist_Helper_Data" helper class, but I have no idea how to build a check-if-already-in-wishlist function. Basically I need to use Magento's wishlist feature to build a favorites list. I want to add a special class to the "add to wishlist" link if the particular product was already added to the user's favorites.
<?php $wishlist = Mage::getModel('wishlist/item')->load($_product->getId(),'product_id');
if($wishlist->getId())
//product is added
echo "Added! - Product is in the wishlist!";
else
//add product to wishlist
echo "<a href='".$this->helper('wishlist')->getAddUrl($_product) ."'>Add This?</a>";
;?>
Since collections are lazy loaded, I am assuming you can do something such as:
$_product = ...; // some product object you already have
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $_product->getSku());
if($_productCollection->count() > 0) {
// User already has item in wishlist.
}
You can do similar filtering on other fields, but SKU should be sufficient in this case.
I'm only getting back to this project now, but I took Daniel Sloof's suggestion, and it worked perfectly using the function below:
public function isInWishlist($item)
{
$_productCollection = Mage::helper('wishlist')->getProductCollection()
->addFieldToFilter('sku', $item->getSku());
if($_productCollection->count()) {
return true;
}
return false;
}
This checks to see whether or not a product has been added into the current user's Wishlist. I called it my template file like this:
if ($this->helper('wishlist')->isInWishlist($_product)) :
I found this solution after checked select query of Mage::helper('wishlist')->getWishlistItemCollection(). I hope this solution help to someone.
/**
* Check customers wishlist on identity product.
* #param Mage_Catalog_Model_Product $_product
* #return bool
*/
private function _isInWishlist($_product)
{
$_productCollection = Mage::helper('wishlist')->getWishlistItemCollection()
->addFieldToFilter('product_id', $_product->getId());
if ($_productCollection->count()) {
return true;
}
return false;
}
I solved this by the below function. I Hope this may help some one.
function checkInWishilist($_product){
Mage::getSingleton('customer/session')->isLoggedIn();
$session = Mage::getSingleton('customer/session');
$cidData = $session->isLoggedIn();
$customer_id = $session->getId();
if($customer_id){
$wishlist = Mage::getModel('wishlist/item')->getCollection();
$wishlist->getSelect()
->join(array('t2' => 'wishlist'),
'main_table.wishlist_id = t2.wishlist_id',
array('wishlist_id','customer_id'))
->where('main_table.product_id = '.$_product->getId().' AND t2.customer_id='.$customer_id);
$count = $wishlist->count();
$wishlist = Mage::getModel('wishlist/item')->getCollection();
}
else {
$count="0";
}
if ($count) :
return true;
else:
return false;
endif;
}
Since #alexadr.parhomenk s' solution causes undesired results, here's a smaller method that does the trick:
/**
* Check customers wishlist on identity product.
* #param int $productId
* #return bool
*/
public function isInWishlist($productId)
{
$ids = Mage::registry('wishlist_ids');
if (!$ids) {
$productCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$ids = $productCollection->getColumnValues('product_id');
Mage::register('wishlist_ids', $ids);
}
return in_array($productId, $ids);
}

Resources