<?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; database</title>
	<atom:link href="http://subesh.com.np/tag/database/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>Generating Invoice/Order&#039;s Next Increment ID in Magento</title>
		<link>http://subesh.com.np/2010/12/generating-invoiceorders-next-increment-id-in-magento/</link>
		<comments>http://subesh.com.np/2010/12/generating-invoiceorders-next-increment-id-in-magento/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 08:32:40 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Model]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=294</guid>
		<description><![CDATA[Magento has its own way of generating increment ID for new invoices and new orders after they are saved. But how about knowing them before hand, i.e before the invoice or the order is created! Lets first understand the working of those increment ID generation before jumping to the code. As all of us must [...]]]></description>
			<content:encoded><![CDATA[<p>Magento has its own way of generating increment ID for new invoices and new orders after they are saved. But how about knowing them before hand, i.e before the invoice or the order is created! Lets first understand the working of those increment ID generation before jumping to the code. As all of us must have known there are &#8220;Entity Types&#8221; in Magento. And those &#8220;Entity Types&#8221; are stored in table named <strong><em>eav_entity_type</em></strong>. If you look into that table for <strong>entity_type_code = order or invoice</strong>, in <strong>increment_model</strong> column you can see the Model alias used to generate new increment ID code. Lets take the case of invoice..so the increment model is <strong><em>eav/entity_increment_numeric</em></strong> and additionally this increment is store dependent as for this row <strong><em>increment_per_store</em></strong> is set to 1.</p>
<p>Next place to look into will be .. Yes! the model <strong><em>eav/entity_increment_numeric</em></strong>. And if you see the model class <strong>Mage_Eav_Model_Entity_Increment_Numeric</strong> there is only one Method in this class the <em>public function getNextId()</em> which is responsible to the the Next increment ID, needless to say its parent has other methods as well since you might have already understood. So if some how you can trigger the right Increment Model for any entity type and the call this method, you must get the next increment ID of order/invoice/shippment.</p>
<p>That was the &#8220;prose&#8221; part now lets get down to the &#8220;code poetry&#8221;. Here&#8217;s how you first find the appropriate increment ID and then fetch the new Increment ID.</p>
<pre class="brush: php; title: ; notranslate">
            //Get the Entity Type Increment Model you want, our case invoice
            // @var $entity_type_model Mage_Eav_Model_Entity_Type
            $entity_type_model=Mage::getSingleton('eav/config')-&gt;getEntityType('invoice');

            //Triggering the getNextId() of the Increment Model
            //@var $invoiceNew Mage_Sales_Model_Order_Invoice
            $new_incr_id = $entity_type_model-&gt;fetchNewIncrementId($invoiceNew-&gt;getOrder()-&gt;getStoreId());
</pre>
<p>Now, you have the generated Invoice Increment ID. This can be helpful in cases when you want to do something else before Invoice is created but you want to now the Increment Id before hand. Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/12/generating-invoiceorders-next-increment-id-in-magento/feed/</wfw:commentRss>
		<slash:comments>1</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>Moving Magento Shop from Development Enviornment to Production Enviornment or Production to Local</title>
		<link>http://subesh.com.np/2009/12/moving-magento-shop-development-enviornment-production-enviornment-production-local/</link>
		<comments>http://subesh.com.np/2009/12/moving-magento-shop-development-enviornment-production-enviornment-production-local/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 12:38:33 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[custom options]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[domain]]></category>
		<category><![CDATA[dump]]></category>
		<category><![CDATA[Export]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=170</guid>
		<description><![CDATA[Today, I had really a good chance to move Magento Shop from Development Enviournment to Product Enviornment. On that course I faced some big difficulty in moving the database. I already had the files and DB of the development enviornment, imporing DB was a PIA. I uploaded all the files, which was easy. And next [...]]]></description>
			<content:encoded><![CDATA[<p>Today, I had really a good chance to move Magento Shop from Development Enviournment to Product Enviornment. On that course I faced some big difficulty in moving the database. I already had the files and DB of the development enviornment, imporing DB was a PIA. I uploaded all the files, which was easy. And next thing I did was uploaded DB dumpped files to root of Magento. Then I logged into SSH and logged into MYSQL. Then Used the following commands to import the dumpped DB files. But first made the database say &#8220;magento&#8221;.</p>
<pre class="brush: sql; title: ; notranslate">
/**Using the Previously created DB**/
mysql&gt; use magento

/**Import the Dumpped SQL**/
mysql&gt;source pathToMagentoRoot/mySql.sql
</pre>
<p>So after the command is executed I had the whole DB on production enviornment. Similarly we can also import dumpped data of Production on Local database running on WAMP server.<br />
To import Dumpped SQL data on WAMP, first create a database, say magento and then use the following commands</p>
<pre class="brush: sql; title: ; notranslate">
/**
	Using the Previously created DB.
	-p password part is optional if you have not configured password for MYSQL locally
	-u Username (root by default)
**/

mysql&gt; C:\wamp\bin\mysql\mysql5.0.51b\bin&gt;mysql.exe -use magento -u root -p password

/**Import the Dumpped SQL**/
mysql&gt;source pathToSQLSource/mySql.sql
</pre>
<p>By Now we have the database synced between Local and Production. Next is configuring the database name used by Magento. Browse to app/etc/local.xml and change in the following part.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;connection&gt;
                    &lt;host&gt;&lt;![CDATA[localhost]]&gt;&lt;/host&gt;
                    &lt;username&gt;&lt;![CDATA[username_here]]&gt;&lt;/username&gt;
                    &lt;password&gt;&lt;![CDATA[password_here]]&gt;&lt;/password&gt;
                    &lt;dbname&gt;&lt;![CDATA[databasename_here]]&gt;&lt;/dbname&gt;
                    &lt;active&gt;1&lt;/active&gt;
    &lt;/connection&gt;
</pre>
<p>Finally, browsed through table core_config_data and find value of path: web/unsecure/base_url and path: web/secure/base_url and change their values accordingly.</p>
<p>Now I had my Shop enviorment switched. Most work for you as well. LOL.</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2009/12/moving-magento-shop-development-enviornment-production-enviornment-production-local/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

