23.02.2015 Views

www.it-ebooks.info

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3<br />

As result of our query, we should see a result set w<strong>it</strong>h three columns: product_id,<br />

product_name, and product_sku. So, let's step back for a second in order to get<br />

product names w<strong>it</strong>h SKUs. W<strong>it</strong>h raw SQL, we would have to wr<strong>it</strong>e a five-line SQL<br />

query, and we would only be retrieving two values from our products: from one<br />

single EAV value table if we wanted to retrieve a numeric field, such as price, or<br />

from a text value, such as product.<br />

If we didn't have an ORM in place, maintaining Magento would be almost<br />

impossible. Fortunately, we do have an ORM in place, and most likely, you will<br />

never need to deal w<strong>it</strong>h raw SQL for working w<strong>it</strong>h Magento.<br />

That said, let's see how can we retrieve the same product <strong>info</strong>rmation by using the<br />

Magento ORM:<br />

1. Our first step is going to instantiate a product collection:<br />

$collection = Mage::getModel('catalog/product')->getCollection();<br />

2. Then, we will specifically tell Magento to select the name attribute:<br />

$collection->addAttributeToSelect('name');<br />

3. Now sort the collection by name:<br />

$collection->setOrder('name', 'asc');<br />

4. And, finally, we will tell Magento to load the collection:<br />

$collection->load();<br />

5. The end result is a collection of all products in the store sorted by name; we<br />

can inspect the actual SQL query by running:<br />

echo $collection->getSelect()->__toString();<br />

W<strong>it</strong>h the help of only three lines of code, we are able to tell Magento to grab all the<br />

products in the store to specifically select the name, and finally, order the products<br />

by the name.<br />

The last line, $collection->getSelect()->__toString(), allows<br />

us to see the actual query that Magento is executing on our behalf.<br />

The actual query being generated by Magento is:<br />

SELECT `e`.*. IF( at_name.value_id >0, at_name.value, at_name_default.<br />

value ) AS `name`<br />

FROM `catalog_product_ent<strong>it</strong>y` AS `e`<br />

LEFT JOIN `catalog_product_ent<strong>it</strong>y_varchar` AS `at_name_default` ON<br />

(`at_name_default`.`ent<strong>it</strong>y_id` = `e`.`ent<strong>it</strong>y_id`)<br />

[ 73 ]<br />

<strong>www</strong>.<strong>it</strong>-<strong>ebooks</strong>.<strong>info</strong>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!