Magento Expert Forum - Improve your Magento experience

Results 1 to 2 of 2

Creating EAV based model(s) in Magento

  1. #1
    Junior Member jaredovi's Avatar
    Join Date
    Mar 2013
    Posts
    69
    Thanks
    2
    Thanked 11 Times in 8 Posts

    Default Creating EAV based model(s) in Magento


    Magento EAV (Entity Attribute Value) data model is used to get flexibility for your data, but it brings more complexity than relation table model. If you need data model that will have flexible attributes which can be dynamically added, for example from Magento admin panel, then EAV is the best solution for you. If using EAV, you don’t need to change table structure for every new attribute like you do on flat tables (creating new colums).

    Bad things which EAV flexibility brings are slower Queries and more complex table structures. Let’s talk more about performance, EAV system is slower than using flat table for resource model, because it uses a lot of mysql joins (depend on attributes number) and, as we know, Query with join data from other tables is always slower than select Query from one table. This problem can be solved with two solutions. For Enterprise Magento enable full page cache and page will be cached, so with or without EAV there won’t be any difference, only first load(slower for EAV) and after that all is cached. Second solution is to make flat table and indexer for creating table from EAV entity attributes.

    After short brief about good and bad things with EAV let’s see how to create custom EAV model in example. For demonstration purposes let’s create Blog module with EAV resource model for posts, and focus will be on creating model, resource model and collection for post with installation. Admin part for adding new posts and custom attributes won’t be part of this article because they’re not required for our EAV model to work. I will demonstrate how to use EAV resurce model and Collection to get post(s) on frontend.

    First we need to create our Blog module by adding module declaration in config, for this we’ll create Inchoo_Blog.xml in app\etc\modules\:
    app\etc\modules\Inchoo_Blog.xml:


    HTML Code:
    <?xml&#91;/B&#93; version="1.0"&#91;B&#93;?>
    <!--
    Inchoo Blog Module
    Author: Zoran Šalamun([email protected])
    https://inchoo.net/
    -->
    [B]<config>[/B]
      [B]<modules>[/B]
        [B]<Inchoo_Blog>[/B]
          [B]<active>[/B]true[B]</active>[/B]
          [B]<codePool>[/B]local[B]</codePool>[/B]
        [B]</Inchoo_Blog>[/B]
      [B]</modules>[/B]
    [B]</config>[/B]
    After registering our module, next step is to create folder structure for Module (Block, Helper, controllers, etc, Model and sql folders in module root folder – app\code\local\Inchoo\Blog\), and inside etc folder config.xml for module configuration:


    HTML Code:
    [B]<?xml&#91;/B&#93; version="1.0"&#91;B&#93;?>[/B]
    <!--
      Blog - Module for testing custom EAV tables
      Author: Zoran Šalamun([email protected])
    -->
    [B]<config>[/B]
      [B]<modules>[/B]
        [B]<Inchoo_Blog>[/B]
          [B]<version>[/B]1.0.0.0[B]</version>[/B]
        [B]</Inchoo_Blog>[/B]
      [B]</modules>[/B]
      [B]<global>[/B]
        [B]<models>[/B]
          [B]<inchoo_blog>[/B]
            [B]<class>[/B]Inchoo_Blog_Model[B]</class>[/B]
          [B]</inchoo_blog>[/B]
        [B]</models>[/B]
        [B]<helpers>[/B]
          [B]<inchoo_blog>[/B]
            [B]<class>[/B]Inchoo_Blog_Helper[B]</class>[/B]
          [B]</inchoo_blog>[/B]
        [B]</helpers>[/B]
        [B]<blocks>[/B]
          [B]<inchoo_blog>[/B]
            [B]<class>[/B]Inchoo_Blog_Block[B]</class>[/B]
          [B]</inchoo_blog>[/B]
        [B]</blocks>[/B]
      [B]</global>[/B]
    [B]</config>[/B]
    In config file we add common options by declaring module version, models, helpers, blocks. After adding them, we add other config options needed for our module to work with entity tables. In config file we have declared model class so Magento can know what model to use with Mage::getModel.

    For Blog posts we need to create post model, post resource model and post collection. First we’ll create post model in app/code/local/Inchoo/Blog/Model/ with file name Post.php:


    PHP Code:
    [B]class[/BInchoo_Blog_Model_Post [B]extends[/BMage_Core_Model_Abstract
    {
     

    Note that Inchoo_Blog_Model_Post class extends Mage_Core_Model_Abstract, same as every other Model, but EAV magic starts in resource model. In post model class we need to define our resource model in _construct():


    PHP Code:
    [B]protected[/B] [B]function[/B_construct()
      {
        
    $this->_init('inchoo_blog/post');
      } 
    inchoo_blog/post is resource model that need to be declared in our config.xml and we’ll add it now in models node:


    HTML Code:
    <models>
          <inchoo_blog>
            <class>Inchoo_Blog_Model</class>
            <resourceModel>inchoo_blog_resource</resourceModel>
          </inchoo_blog>
          <inchoo_blog_resource>
            <class>Inchoo_Blog_Model_Resource</class>
          </inchoo_blog_resource>
        </models>
    inchoo_blog is model node name and post is file name for resource model. Magento creates path to resource model joining inchoo_blog resource class (Inchoo_Blog_Model_Resource) with resource model name (Post). After Magento join this from configuration we’ll get post resource class name (and path): Inchoo_Blog_Model_Resource_Post.

    Now it’s time to create our resource model, so let’s create Post.php file in app/code/local/Inchoo/Blog/Model/Resource/ folder:


    PHP Code:
    [B]class[/BInchoo_Blog_Model_Resource_Post [B]extends[/BMage_Eav_Model_Entity_Abstract
    {
     

    As you can see, our resurce model Inchoo_Blog_Model_Resource_Post extends Mage_Eav_Model_Entity_Abstract and this is how Magento handle EAV in resource model. To make this work with Entity tables we need to set options and default attributes, so to set options we’ll add this code:


    PHP Code:
    [B]public[/B] [B]function[/B__construct()
      {
        
    $resource Mage::getSingleton('core/resource');
        
    $this->setType('inchoo_blog_post');
        
    $this->setConnection(
          
    $resource->getConnection('blog_read'),
          
    $resource->getConnection('blog_write')
        );
      } 
    As you can see, we need to set resource and connection. For connection read and write we need to add in our module config file nodes where we define read and write connections:


    HTML Code:
    <resources>
          <blog_write>
            <connection>
              <use>core_write</use>
            </connection>
          </blog_write>
          <blog_read>
            <connection>
              <use>core_read</use>
            </connection>
          </blog_read>
        </resources>
    $this->setType (‘inchoo_blog_post’) in our Post resource model init defines what entity type resource should be used. We’ll define this later in our module install script. Also in resource model we need to specify default attributes in _getDefaultAttributes() method:


    PHP Code:
    [B]protected[/B] [B]function[/B_getDefaultAttributes()
      {
        return array(
          
    'entity_type_id',
          
    'attribute_set_id',
          
    'created_at',
          
    'updated_at',
          
    'increment_id',
          
    'store_id',
          
    'website_id'
        
    );
      } 
    These are default attributes that will be loaded, but we’ll get back on them later. They’re not required to set because Mage_Eav_Model_Entity_Abstract already set them. You can do it only if you want to change default attributes.

    After creating our resource model we need to create collection class, and we need to create it in app/code/local/Inchoo/Blog/Model/Resource/Post folder with file called Collection.php and that class has to extend EAV collection class abstract:


    PHP Code:
    [B]class[/BInchoo_Blog_Model_Resource_Post_Collection [B]extends[/BMage_Eav_Model_Entity_Collection_Abstract
    {
     
      
    [B]protected[/B] [B]function[/B_construct()
      {
        
    $this->_init('inchoo_blog/post');
      }
     

    We have extended our collection class Inchoo_Blog_Model_Resource_Post_Collection with Mage_Eav_Model_Entity_Collection_Abstract and this gives us options for our resource model to work with EAV tables. As you can see, you need to set resource model like on any other collection ($this->_init(‘inchoo_blog/post’)).

    After setting our model, resource model and collection we have created all functionalities that make this work with EAV. But, one more important step is required to make this actually work – create entity tables and add entity type. We’ll do this with our install script, first we need to set this in our config file:


    HTML Code:
    [B]<resources>[/B]
          [B]<inchoo_blog_setup>[/B]
            [B]<setup>[/B]
              [B]<module>[/B]Inchoo_Blog[B]</module>[/B]
              [B]<class>[/B]Inchoo_Blog_Model_Resource_Setup[B]</class>[/B]
            [B]</setup>[/B]
            [B]<connection>[/B]
              [B]<use>[/B]core_setup[B]</use>[/B]
            [B]</connection>[/B]
          [B]</inchoo_blog_setup>[/B]
        [B]</resources>[/B]
    Now we need to create two things, as you can see in configuration, we need Inchoo_Blog_Model_Resource_Setup class for our setup and setup file for version 1.0.0.0 like our version of module is. Setup class is needed for specifying what attributes model can save in entity tables, and we’ll use this class in our setup script. Let’s create our setup class in app/code/local/Inchoo/Blog/Model/Resource/:


    PHP Code:
    [B]<?php[/B]
     
    [B]class[/BInchoo_Blog_Model_Resource_Setup [B]extends[/BMage_Eav_Model_Entity_Setup
    {
      / 
        
    Setup attributes for inchoo_blog_post entity type
        
    -this attributes will be saved in db if you set them
       
    /
      [
    B]public[/B] [B]function[/BgetDefaultEntities()
      {
        
    $entities = array(
          
    'inchoo_blog_post' => array(
            
    'entity_model' => 'inchoo_blog/post',
            
    'attribute_model' => '',
            
    'table' => 'inchoo_blog/post_entity',
            
    'attributes' => array(
              
    'title' => array(
                
    'type' => 'varchar',
                
    'backend' => '',
                
    'frontend' => '',
                
    'label' => 'Title',
                
    'input' => 'text',
                
    'class' => '',
                
    'source' => '',
                
    'global' => 0,
                
    'visible' => [B]true[/B],
                
    'required' => [B]true[/B],
                
    'user_defined' => [B]true[/B],
                
    'default' => '',
                
    'searchable' => [B]false[/B],
                
    'filterable' => [B]false[/B],
                
    'comparable' => [B]false[/B],
                
    'visible_on_front' => [B]true[/B],
                
    'unique' => [B]false[/B],
              ),
              
    'author' => array(
                
    'type' => 'varchar',
                
    'backend' => '',
                
    'frontend' => '',
                
    'label' => 'Author',
                
    'input' => 'text',
                
    'class' => '',
                
    'source' => '',
                
    'global' => 0,
                
    'visible' => [B]true[/B],
                
    'required' => [B]true[/B],
                
    'user_defined' => [B]true[/B],
                
    'default' => '',
                
    'searchable' => [B]false[/B],
                
    'filterable' => [B]false[/B],
                
    'comparable' => [B]false[/B],
                
    'visible_on_front' => [B]false[/B],
                
    'unique' => [B]false[/B],
              ),
            ),
          )
        );
        return 
    $entities;
      }
    }

    You can see that our setup class extends Mage_Eav_Model_Entity_Setup and we’ve defined our entities and attributes. For entity is used inchoo_blog_post and that’s our entity typeThis needs to be declared in our setup script and we’ve set it also in our post resource modelThis is important step because we must set our attributes for entity model so our resource model can save them in entity tables.

    For 
    example, if our blog should have an authorwe need to specify author attribute in getDefaultEntities method under our inchoo_blog_post entity attributes. If you don’t set attribute and use save on post modelMagento won’t know where to save data and your attribute won’t be savedGood thing with attributes is that they’re only saved in tables, if you set thembut if you don’t set (for example authoron post and saveit will not save this attributeThis approach saves db space in comparison with flat table, as we knowflat table will have all attributes as columns and that columns have NULL value. And that is the biggest advantage of using EAVespecially if you have a lot attributes which are in most cases set for some blog posts.

    One more important advantage in using EAV is to have attributes that will work for different languages(stores), you can see example of this in category/product EAVWhen comparing flat table vs EAVEAV advantages are that flat for some attributes can have mostly NULL values, and if you use EAV all attributes that have not been set won’t be saved anywhere – they will be saved only if you set them.

    Lastly, for our post model to workwe need to make setup script for creating tables and to add entity type with attributes. If you check setup for catalog/product or customeryou can see that every table for EAV is created separately by installerThis approach is good if you want some additional columns in main entity table, if you don’t need that than create EntityTablesthis method is best to use because it will automatically create all EAV tables (note that in 1.6 and 1.7 users reported bugs with this functionality). For our EAV to work we need main entity table (_entity at end of table name) and 6 additional tables for every data type to be saved. For exampleevery time you create a new blog post a new entity will be added to main entity table, and attributes to entity specific type tables (for example varchar type attribute to table that ends with _entity_varchar) if you’ve set attributeEvery attribute is new entry in specific attribute type tableso if you have set 5 attributes there will be 5 entries times stores(if you have 3 storesit will be 15 entries – 5 attributes x 3 stores) in entity tables.

    We have defined setup script with defining setup class and now it’s time to define our tablesTo do thatwe only need to define main entity table namebut for demonstration we’ll define all entity tables to demonstrate how to create all entity tables by creating them separatelyIn configuration file under inchoo_blog_resources node we’ll add tables configuration:


    [
    B]<inchoo_blog_resource>[/B]
            [
    B]<class>[/B]Inchoo_Blog_Model_Resource[B]</class>[/B]
            [
    B]<entities>[/B]
              [
    B]<post_entity>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity[B]</table>[/B]
              [
    B]</post_entity>[/B]
              [
    B]<post_entity_datetime>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_datetime[B]</table>[/B]
              [
    B]</post_entity_datetime>[/B]
              [
    B]<post_entity_decimal>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_decimal[B]</table>[/B]
              [
    B]</post_entity_decimal>[/B]
              [
    B]<post_entity_int>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_int[B]</table>[/B]
              [
    B]</post_entity_int>[/B]
              [
    B]<post_entity_text>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_text[B]</table>[/B]
              [
    B]</post_entity_text>[/B]
              [
    B]<post_entity_varchar>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_varchar[B]</table>[/B]
              [
    B]</post_entity_varchar>[/B]
              [
    B]<post_entity_char>[/B]
                [
    B]<table>[/B]inchoo_blog_post_entity_char[B]</table>[/B]
              [
    B]</post_entity_char>[/B]
            [
    B]</entities>[/B]
          [
    B]</inchoo_blog_resource>[/B]

    View more threads in the same category:


  2. #2
    Junior Member jaredovi's Avatar
    Join Date
    Mar 2013
    Posts
    69
    Thanks
    2
    Thanked 11 Times in 8 Posts

    Default

    For creating tables with createEntityTables we only need post_entity definition and to create all entity tables in install script with createTable, we need all other table definitions.

    Now we’ll create install script, for our version (1.0.0.0), name for install file will be install-1.0.0.0.php. First, we’ll create install script that uses createEntityTables:


    PHP Code:
    $installer $this;
    $installer->startSetup();
     

      
    Create all entity tables
     
    /
    $installer->createEntityTables(
      
    $this->getTable('inchoo_blog/post_entity')
    );
     

      
    Add Entity type
     
    /
    $installer->addEntityType('inchoo_blog_post',Array(
      
    'entity_model'     =>'inchoo_blog/post',
      
    'attribute_model'    =>'',
      
    'table'         =>'inchoo_blog/post_entity',
      
    'increment_model'    =>'',
      
    'increment_per_store'  =>'0'
    ));
     
    $installer
    ->installEntities();
     
    $installer
    ->endSetup(); 
    So, we have set installer, $this refers to our setup class (we have defined that in config file). After setting the installer we have created tables with createEntityTables. This method has created following tables:

    PHP Code:
    inchoo_blog_post_entity
    inchoo_blog_post_entity_datetime
    inchoo_blog_post_entity_decimal
    inchoo_blog_post_entity_int
    inchoo_blog_post_entity_text
    inchoo_blog_post_entity_varchar
    inchoo_blog_post_entity_char 
    inchoo_blog_post_entity is main entity table, and 6 other tables are data type specific for attributes.

    After creating tables we added new entity type with addEntityType, so let’s explain params:

    entity_model – our model which will be used for entity (must have resource that extends Mage_Eav_Model_Entity_Abstract)
    attribute_model – if you want to use other attribute model, remember that attribute models are not limited to 6 standard models and you can create your own
    table – our main entity table
    increment_model – model responsible for generating increment IDs
    increment_per_store – use increment ID per store(1)

    Last thing in install script is to install our entities with installEntities(), which we have defined in setup class (getDefaultEntities). Entity type is added to eav_entity_type table and this is Magento core table for entity types.

    I want to show you code for install script to create all entity tables manually:


    PHP Code:
    [B]<?php[/B]
     
    $installer 
    $this;
    $installer->startSetup();
     

      
    Create table 'inchoo_testeav/entity'
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity'))
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
        
    'unsigned' => [B]true[/B],
       ), 
    'Entity Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_set_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Set Id')
      ->
    addColumn('increment_id'Varien_Db_Ddl_Table::TYPE_TEXT50, array(
        
    'nullable' => [B]false[/B],
        
    'default'  => '',
      ), 
    'Increment Id')
      ->
    addColumn('store_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Store Id')
      ->
    addColumn('created_at'Varien_Db_Ddl_Table::TYPE_TIMESTAMP, [B]null[/B], array(
        
    'nullable' => [B]false[/B],
      ), 
    'Created At')
      ->
    addColumn('updated_at'Varien_Db_Ddl_Table::TYPE_TIMESTAMP, [B]null[/B], array(
        
    'nullable' => [B]false[/B],
      ), 
    'Updated At')
      ->
    addColumn('is_active'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '1',
      ), 
    'Defines Is Entity Active')
      ->
    addIndex($this->getIdxName($baseTableName, array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($this->getIdxName($baseTableName, array('store_id')),
        array(
    'store_id'))
      ->
    addForeignKey($this->getFkName($baseTableName'entity_type_id''eav/entity_type''entity_type_id'),
        
    'entity_type_id'$this->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($this->getFkName($baseTableName'store_id''core/store''store_id'),
        
    'store_id'$this->getTable('core/store'), 'store_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Post Entity Main Table');
    $installer->getConnection()->createTable($table);
     

      
    Datetime entity table for blog post
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity_datetime'))
      ->
    addColumn('value_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
      ), 
    'Value Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Id')
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Id')
      ->
    addColumn('value'Varien_Db_Ddl_Table::TYPE_DATETIME, [B]null[/B], array(
        
    'nullable' => [B]false[/B],
        
    'default' => $installer->getConnection()->getSuggestedZeroDate()
      ), 
    'Value')
      ->
    addIndex(
        
    $installer->getIdxName(
          
    'inchoo_blog_post_entity_datetime',
          array(
    'entity_id''attribute_id'),
          
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
        
    ),
        array(
    'entity_id''attribute_id'),
        array(
    'type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
      ->
    addIndex($installer->getIdxName('inchoo_blog_post_entity_datetime', array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog_post_entity_datetime', array('attribute_id')),
        array(
    'attribute_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog_post_entity_datetime', array('entity_id')),
        array(
    'entity_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog_post_entity_datetime', array('entity_id''attribute_id''value')),
        array(
    'entity_id''attribute_id''value'))
      ->
    addForeignKey(
        
    $installer->getFkName('inchoo_blog_post_entity_datetime''attribute_id''eav/attribute''attribute_id'),
        
    'attribute_id'$installer->getTable('eav/attribute'), 'attribute_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey(
        
    $installer->getFkName('inchoo_blog_post_entity_datetime''entity_id''inchoo_blog/post_entity_datetime''entity_id'),
        
    'entity_id'$installer->getTable('inchoo_blog/post_entity_datetime'), 'entity_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey(
        
    $installer->getFkName(
          
    'inchoo_blog_post_entity_datetime',
          
    'entity_type_id',
          
    'eav/entity_type',
          
    'entity_type_id'
        
    ),
        
    'entity_type_id'$installer->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Blog Post Entity Datetime');
    $installer->getConnection()->createTable($table);
     

      
    Decimal entity table for blog post
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity_decimal'))
      ->
    addColumn('value_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
      ), 
    'Value Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Id')
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Id')
      ->
    addColumn('value'Varien_Db_Ddl_Table::TYPE_DECIMAL'12,4', array(
        
    'nullable' => [B]false[/B],
        
    'default'  => '0.0000',
      ), 
    'Value')
      ->
    addIndex(
        
    $installer->getIdxName(
          
    'inchoo_blog/post_entity_decimal',
          array(
    'entity_id''attribute_id'),
          
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
        
    ),
        array(
    'entity_id''attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_decimal', array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_decimal', array('attribute_id')),
        array(
    'attribute_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_decimal', array('entity_id')),
        array(
    'entity_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_decimal', array('entity_id''attribute_id''value')),
        array(
    'entity_id''attribute_id''value'))
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_decimal''attribute_id''eav/attribute''attribute_id'),
        
    'attribute_id'$installer->getTable('eav/attribute'), 'attribute_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_decimal''entity_id''customer/entity''entity_id'),
        
    'entity_id'$installer->getTable('inchoo_blog/post_entity'), 'entity_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey(
        
    $installer->getFkName('inchoo_blog/post_entity_decimal''entity_type_id''eav/entity_type''entity_type_id'),
        
    'entity_type_id'$installer->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Blog Post Entity Decimal');
    $installer->getConnection()->createTable($table);
     

      
    Integer entity table for blog post
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity_int'))
      ->
    addColumn('value_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
      ), 
    'Value Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Id')
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Id')
      ->
    addColumn('value'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Value')
      ->
    addIndex(
        
    $installer->getIdxName(
          
    'inchoo_blog/post_entity_int',
          array(
    'entity_id''attribute_id'),
          
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
        
    ),
        array(
    'entity_id''attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_int', array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_int', array('attribute_id')),
        array(
    'attribute_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_int', array('entity_id')),
        array(
    'entity_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_int', array('entity_id''attribute_id''value')),
        array(
    'entity_id''attribute_id''value'))
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_int''attribute_id''eav/attribute''attribute_id'),
        
    'attribute_id'$installer->getTable('eav/attribute'), 'attribute_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_int''entity_id''customer/entity''entity_id'),
        
    'entity_id'$installer->getTable('inchoo_blog/post_entity'), 'entity_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_int''entity_type_id''eav/entity_type''entity_type_id'),
        
    'entity_type_id'$installer->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Blog Post Entity Int');
    $installer->getConnection()->createTable($table);
     

      
    Text entity table for blog post
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity_text'))
      ->
    addColumn('value_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
      ), 
    'Value Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Id')
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Id')
      ->
    addColumn('value'Varien_Db_Ddl_Table::TYPE_TEXT'64k', array(
        
    'nullable' => [B]false[/B],
      ), 
    'Value')
      ->
    addIndex(
        
    $installer->getIdxName(
          
    'inchoo_blog/post_entity_text',
          array(
    'entity_id''attribute_id'),
          
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
        
    ),
        array(
    'entity_id''attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_text', array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_text', array('attribute_id')),
        array(
    'attribute_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_text', array('entity_id')),
        array(
    'entity_id'))
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_text''attribute_id''eav/attribute''attribute_id'),
        
    'attribute_id'$installer->getTable('eav/attribute'), 'attribute_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_text''entity_id''customer/entity''entity_id'),
        
    'entity_id'$installer->getTable('inchoo_blog/post_entity'), 'entity_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey(
        
    $installer->getFkName('inchoo_blog/post_entity_text''entity_type_id''eav/entity_type''entity_type_id'),
        
    'entity_type_id'$installer->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Blog Post Entity Text');
    $installer->getConnection()->createTable($table);
     

      
    Varchar entity table for blog post
     
    /
    $table $installer->getConnection()
      ->
    newTable($installer->getTable('inchoo_blog/post_entity_varchar'))
      ->
    addColumn('value_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'identity' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'primary'  => [B]true[/B],
      ), 
    'Value Id')
      ->
    addColumn('entity_type_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Type Id')
      ->
    addColumn('attribute_id'Varien_Db_Ddl_Table::TYPE_SMALLINT, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Attribute Id')
      ->
    addColumn('entity_id'Varien_Db_Ddl_Table::TYPE_INTEGER, [B]null[/B], array(
        
    'unsigned' => [B]true[/B],
        
    'nullable' => [B]false[/B],
        
    'default'  => '0',
      ), 
    'Entity Id')
      ->
    addColumn('value'Varien_Db_Ddl_Table::TYPE_TEXT255, array(
      ), 
    'Value')
      ->
    addIndex(
        
    $installer->getIdxName(
          
    'inchoo_blog/post_entity_varchar',
          array(
    'entity_id''attribute_id'),
          
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
        
    ),
        array(
    'entity_id''attribute_id'), array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_varchar', array('entity_type_id')),
        array(
    'entity_type_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_varchar', array('attribute_id')),
        array(
    'attribute_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_varchar', array('entity_id')),
        array(
    'entity_id'))
      ->
    addIndex($installer->getIdxName('inchoo_blog/post_entity_varchar', array('entity_id''attribute_id''value')),
        array(
    'entity_id''attribute_id''value'))
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_varchar''attribute_id''eav/attribute''attribute_id'),
        
    'attribute_id'$installer->getTable('eav/attribute'), 'attribute_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey($installer->getFkName('inchoo_blog/post_entity_varchar''entity_id''customer/entity''entity_id'),
        
    'entity_id'$installer->getTable('inchoo_blog/post_entity'), 'entity_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    addForeignKey(
        
    $installer->getFkName('inchoo_blog/post_entity_varchar''entity_type_id''eav/entity_type''entity_type_id'),
        
    'entity_type_id'$installer->getTable('eav/entity_type'), 'entity_type_id',
        
    Varien_Db_Ddl_Table::ACTION_CASCADEVarien_Db_Ddl_Table::ACTION_CASCADE)
      ->
    setComment('Blog Post Entity Varchar');
    $installer->getConnection()->createTable($table);
     

      
    Add Entity type
     
    /
    $installer->addEntityType('inchoo_blog_post',Array(
      
    'entity_model'     =>'inchoo_blog/post',
      
    'attribute_model'    =>'',
      
    'table'         =>'inchoo_blog/post_entity',
      
    'increment_model'    =>'',
      
    'increment_per_store'  =>'0'
    ));
     
    $installer
    ->installEntities();
     
    $installer
    ->endSetup();
    You can see that we removed createEntityTables and defined (also created) all tables manually. This approach can give us some additional columns specific for our needs, and for blog we can create title and content columns. As we know, every blog post needs to have title and content, so there is no need to use attributes for them.

    Testing our code



    For testing purposes we’ll create a route definition and index controller. Let’s define everything in config.xml


    HTML Code:
    <frontend>
        <routers>
          <inchoo_blog>
            <use>standard</use>
            <args>
              <module>Inchoo_Blog</module>
              <frontName>blog</frontName>
            </args>
          </inchoo_blog>
        </routers>
      </frontend>
    As you can see, defined in frontName we’ll use /blog/ for our blog, and for test we’ll use index controller and index action. Url for testing will be http:://ourmagento.com/blog/ or http:://ourmagento.com/blog/index/index/ (if we only write /blog/ magento will know that index is controller and index is action if not defined otherwise).

    For testing we’ll now create index controller with index action:


    PHP Code:
    [B]class[/BInchoo_Blog_IndexController [B]extends[/BMage_Core_Controller_Front_Action
    {
      [
    B]public[/B] [B]function[/BindexAction()
      {
        / 
          
    Create new blog post with author and title
          
    -this will create new row in inchoo_blog_post_entity table and
          
    two entries for title and author attributes will be saved in inchoo_blog_post_entity_varchar table
         
    /
        
    $post Mage::getModel('inchoo_blog/post');
        
    $post->setTitle('Test title');
        
    $post->setAuthor('Zoran Šalamun');
        
    $post->save();
     
        

          Try 
    to create post with book type attribute
          
    -book type attribute will not be saved because book type attribute is not defined for our entity type
          
    -on new row will be added in inchoo_blog_post_entity
         
    /
        
    $post Mage::getModel('inchoo_blog/post');
        
    $post->setBookType('Test title');
        
    $post->save();
     
        

          
    Getting posts collection
          
    -also load collection
          
    -this will load all post entries but without attributes
          
    -loaded data is only from inchoo_blog_post_entity table
         
    /
        
    $posts Mage::getModel('inchoo_blog/post')->getCollection();
        
    $posts->load();
        
    var_dump($posts);
     
        

          
    Getting post collection
          
    -load all posts
          
    -set attributs to be in collection data
         
    /
        
    $posts Mage::getModel('inchoo_blog/post')->getCollection()
            ->
    addAttributeToSelect('title')
            ->
    addAttributeToSelect('author');
        
    $posts->load();
        
    var_dump($posts);
     
        

          
    Load signle post
          
    -loading single post will get all attributes that we have set for post
         
    /
        
    $post Mage::getModel('inchoo_blog/post')->load(1);
        
    var_dump($post);
      }

    I hope this will help you understand basics for creating EAV models. Also, you can download test module which we’ve used for demonstration here or you can find it on GitHub.

    Source: inchoo

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •