Skip to main content

Magento 2 - New Table and Models


In magento 2, creation of a table and model has changed little bit. Here we will go through how to add them. The blog post describes how to concept of adding or changing database in magento 2. You can find the sample code in the git repo.

As we are going to add new table to the db, we will use InstallSchema.php inside Setup folder. This file will create a table in the database.
namespace VendorName\ModuleName\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\Adapter\AdapterInterface;

class InstallSchema implements InstallSchemaInterface {

    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) {
        $table = $setup->getConnection()
                ->newTable($setup->getTable('table_name'))
                ->addColumn('entity_id', Table::TYPE_INTEGER, null, [
                    'identity' => true,
                    'unsigned' => true,
                    'nullable' => false,
                    'primary' => true,
                        ], 'Main Id')
                ->addColumn('text_column', Table::TYPE_TEXT, 25, [], 'Text Column')
                ->addColumn('updated', Table::TYPE_BOOLEAN, null, [
                    'default' => 0,
                    'nullable' => FALSE,
                        ], 'Updated or not')
                ->addColumn('updated_at', Table::TYPE_TIMESTAMP, null, [
                    'nullable' => true,
                        ], 'Updated date')
                ->setComment('table details');
        $setup->getConnection()->createTable($table);
    }

}


Now we need to create three model files as usual for the table Model, ResouceModel and CollectionModel. Let us make the model name as Mymodel.php. It is almost similar to the magento 1 model.
namespace VendorName\ModuleName\Model;

class Mymodel extends \Magento\Framework\Model\AbstractModel {

    public function _construct() {
        $this->_init('VendorName\ModuleName\Model\ResourceModel\Mymodel');
    }

}


The resource model will look as below.
namespace VendorName\ModuleName\Model\ResourceModel;

class Mymodel extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {
    
    public function _construct() {
        $this->_init('table_name', 'primary_id');
    }

}


The collection model will look as below.
namespace VendorName\ModuleName\Model\ResourceModel\Mymodel;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection {
    
    public function _construct() {
        $this->_init('VendorName\ModuleName\Model\Mymodel', 'VendorName\ModuleName\Model\ResourceModel\Mymodel');
    }

}

Once you compile the code, a modelfactory, resourcefactory and collectionfactory is created. We can use these factories to create and use the models. e.g. VendorName\ModuleName\Model\MymodelFactory is created for the model.
We can also use objectmanager to load the models. The below code loads the collection is both format.
use VendorName\ModuleName\Model\ResourceModel\Mymodel\CollectionFactory;

class yourclass extends .... {
    
    protected $_myFactory;

    public function __contruct($params, ..., CollectionFactory $myFactory, ...) {
        $this->_myFactory = $myFactory;
    }

    public function somefunction() {
        $collection = $this->_myFactory->create()->getCollection();
        or
        $collection = $this->_objectManager->create('VendorName\ModuleName\Model\ResourceModel\Mymodel')
    }
}

Comments

Popular posts from this blog

Magento 2 - Create Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .