I'm working on magento2 custom module. i have to install some data in my custom_table. so i am referencing below script.

i know the idea about $postFactory as describe here Magento2: How to add pre defined data (installData.php) for Custom Module .

I'm bit confused.
As mentioned below __construct function is calling postFactory:

Is it $postFactory necessary for inseting data??

If yes then my modulename & tabelname both are different so how can i do that ??

namespace Vendor\Modulename\Setup;

use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
    private $_postFactory;

    public function __construct(\Vendor\Modulename\Model\PostFactory $postFactory)
        $this->_postFactory = $postFactory;

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        $data = [
            'title' => 'Hello world!',
            'content_heading' => 'Hello world!',
            'content' => 'logn description put here'


  • Yes it is necessary, it will decide in which table the data will be stored. – KamranKhan Mar 7 '18 at 6:52
  • 1
    If you have custom table then you need to create Resource Model to initialize table and Model to insert data in table. Or you can also use Magento\Framework\App\ResourceConnection class to insert data in table. – Prince Patel Mar 7 '18 at 7:00

Magento2 Extension installData script in modelFactory is necessary?

I can say no.

We have another option: insert data directly to table. BUT using the factory is more convenient. For example, we can add more logic to check the data before inserting into the database. A model factory is for CRUD operations, not just for installing data.

We need to build Model, Resource Model, Collection to fully work with database.

An example how to insert data directly to table: vendor/magento/module-sales/Setup/InstallData.php

| improve this answer | |
  • Thank you for your answer. so my data is just static it is not upgrading in future. so how can i write install script for it? reference please. – Himanshu Mar 7 '18 at 7:14
  • 1
    See this file: vendor/magento/module-sales/Setup/InstallData.php: $setup->getConnection()->update( $setup->getTable('sales_order_status_state'), ['visible_on_front' => 1], ['state = ?' => $state] ); – Khoa TruongDinh Mar 7 '18 at 7:22

Yes it is necessary, it will decide in which table the data will be stored. Magento 2 is came up with the concept of factories.

Just go through this link When Should We Use a Repository and Factory in Magento 2?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.