<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Subesh Pokhrel&#039;s Blog - Magento Development Tips &#187; Query</title>
	<atom:link href="http://subesh.com.np/tag/query/feed/" rel="self" type="application/rss+xml" />
	<link>http://subesh.com.np</link>
	<description>PHP &#38; Magento Tips and Tutorials</description>
	<lastBuildDate>Wed, 01 Feb 2012 04:09:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Custom Query In Magento a Zend Approach [Updated]</title>
		<link>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/</link>
		<comments>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 10:11:05 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=300</guid>
		<description><![CDATA[I&#8217;ve already mentioned about custom query in Magento, before but now I think its time to upgrade that method to next level because it would always be good to have standard code for reference.So it is just a new improved way of using a custom query. First of all we will need is a connection [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve already mentioned about<a href="http://subesh.com.np/2009/12/using-custom-query-in-magento/"> custom query in Magento</a>, before but now I think its time to upgrade that method to next level because it would always be good to have standard code for reference.So it is just a new improved way of using a custom query.<br />
First of all we will need is a connection instance. Lets use default_setup instance because it can used for read and write purpose.</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
</pre>
<p>Then we will use this connection to instanciate Zend_Db_Select object and write query like</p>
<pre class="brush: php; title: ; notranslate">
$select = new Zend_Db_Select($connection);
$table = 'catalog_product_index_price';
$select-&gt;from($table, array('entity_id'))
	-&gt;where('entity_id = ?', $entityId);

// Getting result

$result = $select-&gt;query();
$rowCount = $result-&gt;rowCount();

if ($rowCount) {
	foreach ($result-&gt;fetchAll() as $data) {
		return $data['entity_id'];
	}
}
</pre>
<p>The above one is for select but what about inserting data? It is simple as well. All you have to do is create an associative array of data to be inserted and use connection to add data. For example</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
$table = 'catalog_product_index_price';

$insertData = array();
$insertData ['price'] = $productPrice;
$insertData ['final_price'] = $productPrice;
$insertData ['min_price'] = $productPrice;
$insertData ['max_price'] = $productPrice;
$insertData ['tier_price'] = $productPrice;

$connection-&gt;insert($table, $insertData);
</pre>
<p>I think this should be a good enough code for using custom query in Magento. About Zend_Db_Select please visit <a href="http://framework.zend.com/manual/en/zend.db.select.html">http://framework.zend.com/manual/en/zend.db.select.html</a>.</p>
<p><strong>[UPDATE]</strong></p>
<p>If you want to update the data with custom query and have a condition then you can send the conditions as array as third params to update function. For example.</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
$table = 'catalog_product_index_price';

$updateCond = array(); // Update condition array container.
$insertData = array();
$insertData ['price'] = $productPrice;
$insertData ['final_price'] = $productPrice;
$insertData ['min_price'] = $productPrice;
$insertData ['max_price'] = $productPrice;
$insertData ['tier_price'] = $productPrice;

$updateCond [] = 'store_id = 0';
$updateCond [] = 'entity_id = 3';

$connection-&gt;insert($table, $insertData, $updateCond);
</pre>
<p>Happy Brogramming!!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Analysis &amp; Usage of Collections in Magento</title>
		<link>http://subesh.com.np/2010/05/analysis-usage-collections-magento/</link>
		<comments>http://subesh.com.np/2010/05/analysis-usage-collections-magento/#comments</comments>
		<pubDate>Thu, 13 May 2010 12:20:25 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=246</guid>
		<description><![CDATA[As a Magento Programmer I am fascinated by the use &#38; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we [...]]]></description>
			<content:encoded><![CDATA[<p>As a Magento Programmer I am fascinated by the use &amp; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we are actually trying to get from database. Here is what I found drilling down into the Magento&#8217;s Core. I may be &#8220;not quite right&#8221; with the analysis, you can always comment.</p>
<p>Almost all the collections found inside  <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model/Collection.php</strong> are the child of parent Class <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong>. Primary thing done in the class constructor is initializing its resource and Model. If you look into one of the Collection class you can see in its constructor.</p>
<pre class="brush: php; title: ; notranslate">
/**
	 * @class Mage_Checkout_Model_Mysql4_Agreement_Collection
     * Initialize resource
     *
     */
    protected function _construct()
    {
        $this-&gt;_init('checkout/agreement');
    }
</pre>
<p>And this _init function has been implemented in its parent class as</p>
<pre class="brush: php; title: ; notranslate">
/**
     * Standard resource collection initalization
     *
     * @param string $model
     * @return Mage_Core_Model_Mysql4_Collection_Abstract
     */
    protected function _init($model, $resourceModel=null)
    {
        $this-&gt;setModel($model);
        if (is_null($resourceModel)) {
            $resourceModel = $model;
        }
        $this-&gt;setResourceModel($resourceModel);
        return $this;
    }
</pre>
<p>The resource class can be found in <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model.php</strong>. And this resource class in turn initializes the database table to be used in the Module along with the table&#8217;s primary key.</p>
<pre class="brush: php; title: ; notranslate">
class Mage_Checkout_Model_Mysql4_Agreement extends Mage_Core_Model_Mysql4_Abstract
	{

	protected function _construct()
    {
        $this-&gt;_init('checkout/agreement', 'agreement_id');
    }
	......
	}
</pre>
<p>It is this resource class that actually works out the database connections, read/write adapters and performs transactions. So this is the basic deduction about the link of collection with the database and its tables. But how are those collection formed still remains a mystery, not anymore! In this section of the post I will try to explain how are the collections really formed.</p>
<p>If I can, &#8220;<strong>collection</strong>&#8221; can be defined as collection or array of its resource. And in Magento case, most of the resources are database&#8217;s query results. Simply you can visualize &#8220;<strong>collection</strong>&#8221; to be array of your model&#8217;s resource. If a &#8220;<strong>query</strong>&#8221; in Magento returns a collection of all the products then it would mean that the very collection is an array of all the individual product&#8217;s object. But one question still remains how will the database query&#8217;s result transform into a Magento &#8220;<strong>collection</strong>&#8220;. To understand that we need to understand the collection class and its parents.</p>
<p>The class Structure for <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong> is like this.</p>
<p>Mage_Core_Model_Mysql4_Collection_Abstract</p>
<p style="padding-left: 30px;">|__ Varien_Data_Collection_Db (C)</p>
<p style="padding-left: 60px;">|__	Varien_Data_Collection (C)</p>
<p style="padding-left: 90px;">|__ IteratorAggregate (I)</p>
<p style="padding-left: 90px;">|__ Countable (I)</p>
<p>You can see that all collection implements two Interfaces <strong>IteratorAggregate </strong>&amp; <strong>Countable</strong>.</p>
<p><a href="http://goo.gl/MjAT" target="_blank">IteratorAggregate </a> is predefined in Standard PHP Library that extends Abstract Base Class <a href="http://goo.gl/rzXS" target="_blank">Traversable </a>. On using this Interface you can then <a href="http://goo.gl/hgtI" target="_blank">Iterate Through Object</a> using &#8220;<strong>foreach</strong>&#8221; construct. Countable returns the size of the Collection Object.</p>
<p>Among the two Interfaces, <strong>IteratorAggregate </strong>is particularly important. As you can see in Class Hierarchy both the interfaces are implemented by<strong> Varien_Data_Collection</strong> concrete class. <strong>IteratorAggregate</strong> has abstract public method <strong>getIterator()</strong> which returns the Iterator interface and the concrete Class has to implement the method on its own. It is this Iterator that provides the real iteration functionality. You can get a detailed description about Iterator <a href="http://goo.gl/C9Nx" target="_blank">Here</a>.</p>
<p>So if you look into the <strong>Varien_Data_Collection</strong> you will find the <strong>getIterator()</strong> implemented like this.</p>
<pre class="brush: php; title: ; notranslate">
/**
	 * @class Varien_Data_Collection
     * Implementation of IteratorAggregate::getIterator()
     */
    public function getIterator()
    {
        $this-&gt;load();
        return new ArrayIterator($this-&gt;_items);
    }
</pre>
<p>As you can see that it first loads the &#8220;<strong>items</strong>&#8221; (I will get back to this Items) and instanciates the value to an internal Class <a href="http://goo.gl/8LAi" target="_blank">ArrayIterator </a>. And the Iterator returned by this function can then be iterated using <strong>foreach </strong>construct.</p>
<p>Looks like it is going to be a looonnnnng post, let be summarize what I&#8217;ve tried to point out until now. I&#8217;ve tried to show the link between the collection class or rather object with the database table and explain the iteration behavior of the collection object. But one question still remains how will the database query&#8217;s result transform into a Magento&#8217;s &#8220;<strong>collection</strong>&#8220;. This is where the &#8220;<strong>items</strong>&#8221; explanation need to be done.</p>
<p>&#8220;<strong>Items</strong>&#8221; are actually array if individual object (item) of the collection which represents the array of tuple of the database query result. As you see in the snippet above the <strong>ArrayIterator </strong>takes <strong>$this-&gt;_items</strong> are parameter. But <strong>$this-&gt;_items</strong> are not populated here on <strong>Varien_Data_Collection</strong> but rather on is child class <strong>Varien_Data_Collection_Db</strong>. Here&#8217;s the snippet from Varien_Data_Collection_Db.</p>
<pre class="brush: php; title: ; notranslate">
/**
     * Load data
     * @class Varien_Data_Collection_Db
     * @return  Varien_Data_Collection_Db
     */
    public function load($printQuery = false, $logQuery = false)
    {
        if ($this-&gt;isLoaded()) {
            return $this;
        }

        $this-&gt;_renderFilters()
             -&gt;_renderOrders()
             -&gt;_renderLimit();

        $this-&gt;printLogQuery($printQuery, $logQuery);

		// Getting Data from DB
        $data = $this-&gt;getData();

        $this-&gt;resetData();

        if (is_array($data)) {

		    // Looping on each result row
            foreach ($data as $row) {
			    // Creating Empty &quot;item&quot; Varien_Object's object
                $item = $this-&gt;getNewEmptyItem();

                if ($this-&gt;getIdFieldName()) {
                    $item-&gt;setIdFieldName($this-&gt;getIdFieldName());
                }

				// Setting Varien_Object's values to that of the row
                $item-&gt;addData($row);

				/**
				* Adding the &quot;item&quot; to the collection @class Varien_Data_Collection
				* So while referring to $this-&gt;_items @class Varien_Data_Collection it will return array of this &quot;item&quot;
				*/
                $this-&gt;addItem($item);
            }

        }

        $this-&gt;_setIsLoaded();
        $this-&gt;_afterLoad();
        return $this;
    }

    /**
     * Get all data array for collection
     * @class Varien_Data_Collection_Db
     * @return array
     */
    public function getData()
    {
        if ($this-&gt;_data === null) {
            $this-&gt;_renderFilters()
                 -&gt;_renderOrders()
                 -&gt;_renderLimit();

			// Fetching all the row with the Select query set
            $this-&gt;_data = $this-&gt;_fetchAll($this-&gt;_select);
            $this-&gt;_afterLoadData();
        }
        return $this-&gt;_data;
    }
</pre>
<p>You can go through the inline comments I&#8217;ve added. This is it, I&#8217;ve finally worked out the explanation of structure &amp; creation of Magento&#8217;s Collection and its iterative behavior. I&#8217;ve tried to show pictorially (below) what I have just described. Confused! Plz comment and of course please do comment if I am wrong, because there are &#8220;times&#8221; when you try to understand things even though they actually aren&#8217;t just like you think. I&#8217;d like to quote <strong>Paulo </strong> :<strong><em>&#8220;I see the world in terms of what I would like to see happen, not what actually does&#8221;</em></strong>!</p>
<p><img class="alignnone size-full wp-image-249" title="hierarchy" src="http://subesh.com.np/wp-content/uploads/2010/05/hierarchy.jpg" alt="hierarchy" width="505" height="604" /></p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/05/analysis-usage-collections-magento/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Redirect to some other location from Model or Observer in Magento</title>
		<link>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/</link>
		<comments>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 12:45:02 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Controllers]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=236</guid>
		<description><![CDATA[Redirection in Magento&#8217;s controller is simple. You just need to call a _redirect() or _forward() function and provide appropriate router/controller/action parameter. But if you want to redirect to some other page from Model or from Observer, then this can be tricky. Lets take an example, for explaining what I am referring to, Suppose you are [...]]]></description>
			<content:encoded><![CDATA[<p>Redirection in Magento&#8217;s controller is simple. You just need to call a <strong>_redirect() </strong>or <strong>_forward() </strong>function and provide appropriate router/controller/action parameter. But if you want to redirect to some other page from Model or from Observer, then this can be tricky. Lets take an example, for explaining what I am referring to, Suppose you are building a module that will only allow user of certain group to view a product in frontend. Then, you will have options like:</p>
<ul>
<ol>
Rewrite you catalog/product/view controller and add that logic.
</ol>
<ol>
Rewrite Block of that page and show error message accordingly.
</ol>
<ol>
Any other..?
</ol>
</ul>
<p>Yeha, I do have another option as well. The Event-Observer Method. You can observe an event <strong>controller_action_predispatch_catalog_product_view</strong> and set up an observer where you can write your own logic there and redirect accordingly.</p>
<p>You can observe that event by setting up your config something like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;controller_action_predispatch_catalog_product_view&gt;
	&lt;observers&gt;
		&lt;mymodel&gt;
			&lt;type&gt;singleton&lt;/type&gt;
			&lt;class&gt;mymodel/controller_observer&lt;/class&gt;
			&lt;method&gt;controller_action_predispatch_catalog_product_view&lt;/method&gt;
		&lt;/mymodel&gt;
	&lt;/observers&gt;
&lt;/controller_action_predispatch_catalog_product_view&gt;
</pre>
<p>And on the observer&#8217;s <strong>controller_action_predispatch_catalog_product_view</strong> method, you can check your logic for visibiliy of that product to the logged in user group and redirect if not visible.</p>
<p>Here&#8217;s the main point of this post (Did I take a lot of your time ?), in that same method you can directly redirect using the following snippet of code.</p>
<pre class="brush: php; title: ; notranslate">

Mage::app()-&gt;getResponse()-&gt;setRedirect(Mage::getUrl(&quot;myrouter/mycontroller/noview&quot;));
</pre>
<p>Adding an error message to the session would be a good idea, for user to understand what is happening. Else you can directly call a template in the redirected controller&#8217;s action with appropriate message.</p>
<p>I think this sums up the post for now..and as always hoping it helps somebody and waiting for the response.</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/redirect-location-model-observer-magento/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Product Links in Magento Using Custom Query</title>
		<link>http://subesh.com.np/2010/03/creating-product-links-magento-custom-query/</link>
		<comments>http://subesh.com.np/2010/03/creating-product-links-magento-custom-query/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 06:28:27 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Import/Export]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Import]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=220</guid>
		<description><![CDATA[I&#8217;ve already made a post in this blog about Adding Related Product and other links to Product in Magento . But when I used the method to creating links among product&#8217;s, while importing very large number of products and creating large number of product links, it took a lot of time and resource. So I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve already made a post in this blog about <a href="http://subesh.com.np/2009/11/adding-related-product-and-other-links-to-product-in-magento/">Adding Related Product and other links to Product in Magento </a>. But when I used the method to creating links among product&#8217;s, while importing very large number of products and creating large number of product links, it took a lot of time and resource. So I thought why not give it a try by direclty creating a link using SQL? And YES! it worked.</p>
<p>Below is the code how I created those links using Custom SQL. But I have to tell you that the former methods looks organized, this is just a work around to a situation. You might know what I am trying to say!</p>
<pre class="brush: php; title: ; notranslate">
$resource 	= Mage :: getSingleton( 'core/resource' );
$read= $resource -&gt; getConnection( 'core_read' );
$write= $resource-&gt;getConnection('core_write');
$linkTable=$resource-&gt;getTableName('catalog/product_link');

// Creating Upsell Product link

$write-&gt;query(&quot;INSERT into $linkTable SET
							product_id='&quot;.$productId.&quot;',
							linked_product_id='&quot;.$linkProduct.&quot;',
							link_type_id='&quot;.Mage_Catalog_Model_Product_Link::LINK_TYPE_UPSELL.&quot;'
			&quot;);

// Creating Related Product link

$write-&gt;query(&quot;INSERT into $linkTable SET
							product_id='&quot;.$productId.&quot;',
							linked_product_id='&quot;.$linkProduct.&quot;',
							link_type_id='&quot;.Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED.&quot;'
			&quot;);

// Creating Crosssell Product Link
$write-&gt;query(&quot;INSERT into $linkTable SET
							product_id='&quot;.$productId.&quot;',
							linked_product_id='&quot;.$linkProduct.&quot;',
							link_type_id='&quot;.Mage_Catalog_Model_Product_Link::LINK_TYPE_CROSSSELL.&quot;'
			&quot;);
</pre>
<p>Happy Coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/creating-product-links-magento-custom-query/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Collection of Objects in Magento using a &quot;Magical Class&quot;:Varien_Data_Collection</title>
		<link>http://subesh.com.np/2010/03/creating-collection-objects-magento-magical-classvarien_data_collection/</link>
		<comments>http://subesh.com.np/2010/03/creating-collection-objects-magento-magical-classvarien_data_collection/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 11:58:04 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=215</guid>
		<description><![CDATA[Have you ever wondered how Collection in Magento are built, containing array of individual Entity Objects of Magento? Collections are one of the most important data structure (if I am right) used in Magento. Most of the queries in Magento will result into collection, and then you will apply a foreach loop to access individual [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever wondered how Collection in Magento are built, containing array of individual Entity Objects of Magento? Collections are one of the most important data structure (if I am right) used in Magento. Most of the queries in Magento will result into collection, and then you will apply a foreach loop to access individual Entity Objects and their values. Today I came into a different situation where I had individual objects but needed to create a collection of those objects, so that I could return the collection from a function.</p>
<p>I have not drilled down to the details of collection, untill today when I really need it! Do you think its very late? because I have been into Magento for more than a year now!. Better late than never! So, I got the way of working out my situation. Here is how I created a collection from Magento&#8217;s &#8220;Magical Class&#8221; Varien_Data_Collection. I call this &#8220;Magical Class&#8221;, because it worked like a Magic to me <img src='http://subesh.com.np/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<pre class="brush: php; title: ; notranslate">
$collection=new Varien_Data_Collection();
$collection-&gt;addItem($objProduct);
</pre>
<p>There are various other functions in this class you might need to &#8220;work around&#8221; a problem. So, have a look and certainly do comment if you also think this class to be a Magical Class!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/creating-collection-objects-magento-magical-classvarien_data_collection/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Getting Ordered Items and their Detail from Order ID in Magento</title>
		<link>http://subesh.com.np/2010/03/ordered-items-detail-order-id-magento/</link>
		<comments>http://subesh.com.np/2010/03/ordered-items-detail-order-id-magento/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 12:00:21 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Custom Module]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=213</guid>
		<description><![CDATA[Here is a small snippet of code, yet useful, to get ordered items and its details. I&#8217;ve deviced this code a lot before and posted in Magento Commerce&#8217;s Forum as well. But felt like writting it again, so that I can have a quick refrence to it as well. Next thing, I&#8217;ve tried a lot [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a small snippet of code, yet useful, to get ordered items and its details. I&#8217;ve deviced this code a lot before and posted in Magento Commerce&#8217;s Forum as well. But felt like writting it again, so that I can have a quick refrence to it as well. Next thing, I&#8217;ve tried a lot to get all orders and their items details by single query, but have not yet come up with a solution. If you have any method of finding order and its details by a single query, then please do response. The code below first needs an order ID as it parameters to give order details.</p>
<pre class="brush: php; title: ; notranslate">
$order = Mage::getModel('sales/order')-&gt;load($order_id);
$items = $order-&gt;getAllItems();
$itemcount=count($items);
$name=array();
$unitPrice=array();
$sku=array();
$ids=array();
$qty=array();
foreach ($items as $itemId =&gt; $item)
{
	$name[] = $item-&gt;getName();
	$unitPrice[]=$item-&gt;getPrice();
	$sku[]=$item-&gt;getSku();
	$ids[]=$item-&gt;getProductId();
	$qty[]=$item-&gt;getQtyToInvoice();
}
</pre>
<p>Hope this might &#8220;just&#8221; help somebody in need.</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/03/ordered-items-detail-order-id-magento/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Getting Customer&#039;s Info Using Single Query Including Billing and Shipping Addresses</title>
		<link>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/</link>
		<comments>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 08:49:45 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=184</guid>
		<description><![CDATA[Query in Magento can be quite troublesome, if you are a starter..or non-starter. So I&#8217;ve tried to share some of the difficult queries using collection in Magento, so that it will be helpful to my blog readers and also a place where I can later refer to. Here is one of them, may not be [...]]]></description>
			<content:encoded><![CDATA[<p>Query in Magento can be quite troublesome, if you are a starter..or non-starter. So I&#8217;ve tried to share some of the difficult queries using collection in Magento, so that it will be helpful to my blog readers and also a place where I can later refer to. Here is one of them, may not be dificult to all, but for me I had a very bad time initially, when I first started on Magento about a year ago. I had always thought to post on my blog, but when one of my collegue asked me about this I remembered and here&#8217;s the query.</p>
<pre class="brush: php; title: ; notranslate">
$collection = Mage::getResourceModel('customer/customer_collection')
				-&gt;addNameToSelect()
				-&gt;addAttributeToSelect('email')
				-&gt;addAttributeToSelect('created_at')
				-&gt;addAttributeToSelect('group_id')
				-&gt;joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_fax', 'customer_address/fax', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_country_code', 'customer_address/country_id', 'default_billing', null, 'left')

				-&gt;joinAttribute('shipping_street', 'customer_address/street', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_postcode', 'customer_address/postcode', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_city', 'customer_address/city', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_telephone', 'customer_address/telephone', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_fax', 'customer_address/fax', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_region', 'customer_address/region', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_country_code', 'customer_address/country_id', 'default_shipping', null, 'left')
				-&gt;joinAttribute('taxvat', 'customer/taxvat', 'entity_id', null, 'left');
</pre>
<p>Hope this helps somebody!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Custom Query in Magento</title>
		<link>http://subesh.com.np/2009/12/using-custom-query-in-magento/</link>
		<comments>http://subesh.com.np/2009/12/using-custom-query-in-magento/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 08:33:01 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=133</guid>
		<description><![CDATA[Magento has given us very good features to manage Models and Collection for interacting with Database tables. Nowonder, they are very helpful in most of the cases. Yet, we may need to write custom query in some cases (if you need it quick or if you are new to Models &#38; Collection in Magento). But [...]]]></description>
			<content:encoded><![CDATA[<p>Magento has given us very good features to manage Models and Collection for interacting with Database tables. Nowonder, they are very helpful in most of the cases. Yet, we may need to write custom query in some cases (if you need it quick or if you are new to Models &amp; Collection in Magento). But by Magento&#8217;s standard this is not recommended. If you are a starter you may find this quering to database very helpful. Here is how you can do this.</p>
<p>The idea is simply to get the core connection object and use its functions to run your query.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// For Read

// fetch read database connection that is used in Mage_Core module
$read= Mage::getSingleton('core/resource')-&gt;getConnection('core_read');
$value=$read-&gt;query(&quot;SE...&quot;);
$row = $value-&gt;fetch();

print_r($row); // As Array

// For Write

// fetch write database connection that is used in Mage_Core module
$write = Mage::getSingleton('core/resource')-&gt;getConnection('core_write');

// now $write is an instance of Zend_Db_Adapter_Abstract
$write-&gt;query(&quot;insert into tablename values ('aaa','bbb','ccc')&quot;);

?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2009/12/using-custom-query-in-magento/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to get Query as a String in Magento?</title>
		<link>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/</link>
		<comments>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 13:48:33 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=81</guid>
		<description><![CDATA[Magento as you might know or not! has really a very PIA (Pain in the A**) type of methods to create SQL, execute and fetch! There are two ways of getting SQL from the collection of Magento. Here are the two ways. 1. Only Echoing Query String. For just echoing the query string you must [...]]]></description>
			<content:encoded><![CDATA[<p>Magento as you might know or not! has really a very PIA (Pain in the A**) type of methods to create SQL, execute and fetch! There are two ways of getting SQL from the collection of Magento. Here are the two ways.</p>
<p><strong>1. Only Echoing Query String.</strong><br />
For just echoing the query string you must call printlogquery(), method the the collection. Like.</p>
<pre class="brush: php; title: ; notranslate">
/** If $collection is your collection**/
$collection-&gt;printlogquery(true);
/** Don't forget to write true in param**/
</pre>
<p>But by this method you cannot assign the query you get echoed to some variable. To get the query string here is what you do.</p>
<p><strong>2. Getting the query String</strong></p>
<pre class="brush: php; title: ; notranslate">
$query=$collection-&gt;getSelectSql(true);
echo $query;
</pre>
<p>You can then use this $query to concat with more query, in some cases you desperately need this.</p>
<p>Stay Tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

