Create model in Magento 2

Create model in Magento 2- If you’re creating your own Magento 2 module, may be you will need your extension to be able to create a table during module installation or upgrade process. We will create a model connect with this table also. You can download the package of the last version here

In this turorial, we’re going to create a table named ‘example_member’, insert some rows and create a model connect with that table also.
Let’s note what we will do:
– create a file to create a table during module installation process.
– create a model and resource model connect with the table to retrive, insert or update data.

1. Create file: /app/code/MagentoSharing/Example/Setup/InstallSchema.php

with content:

As you can see, table ‘example_member’ has 4 columns: ‘member_id’, ‘name’, ‘status’ and ‘created_time’.
We will insert some rows to this table in step 2.

2. Create file: /app/code/MagentoSharing/Example/Setup/InstallData.php

with content:

3. Create file: /app/code/MagentoSharing/Example/Model/Member.php

In this file, ‘MagentoSharingExampleModelResourceModelMember’ is class of resource model.

4. Create resource model: /app/code/MagentoSharing/Example/Model/ResourceModel/Member.php

with content:

In this file, ‘example_member’ is table name and ‘member_id’ is the primary key of the table.

5. Create collection resource model: /app/code/MagentoSharing/Example/Model/ResourceModel/Member/Collection.php

with content:

In this file, ‘MagentoSharingExampleModelMember’ is class name of model and ‘MagentoSharingExampleModelResourceModelMember’ is class name of resource model.

6. Please notice:

InstallSchema.php and InstallData.php file is run only one time, the first time you install the module.
So if you already installed this module on your website, please go to table ‘setup_module’ and delete the row contains your module name.

7. Let’s install( or re-install ) this module

using command: php bin/magento setup:upgrade

8. Check if the table is created in database.

We will test model and resource model in example/index/index action.
Edit the file: /app/code/MagentoSharing/Example/Controller/Index/Index.php

Visit http://yourdomain/example/index/index to view result.

Create model in magento 2

You can download the package of this tutorial here

If you have any problems, please leave a comment or contact us.

Thank you for reading.

One thought on “Create model in Magento 2

Leave a Reply

Your email address will not be published.