Creating a New Model with a Database Table in Magento 2

In the world of Magento 2 e-commerce development, there comes a time when you need to extend your store's fonctionality by creating a new model with its associated table de base de données. C'est a crucial skill for développeurs and e-commerce experts looking to customize and enhance their Magento 2 websites. In this comprehensive guide, we'll walk you through the process of creating a new model and table de base de données within Magento 2.

Why Create a New Model and Table?


Creating a custom model and table de base de données is essential when you need to store specific data for your extension or personnalisation. C'est a fundamental part of Magento 2 development and vous permet de manage and retrieve data in an organized manner.

Steps to Create a Model and Database Table

  • Step 1: Create a Custom Module

In your Magento 2 project root répertoire, navigate to the app/code répertoire.
Create a répertoire for your custom module, following the naming convention VendorName_ModuleName. Par exemple, if your company name is "MyCompany" and your module is called "CustomModule," the répertoire structure serait app/code/MyCompany/CustomModule.

  • Step 2: Define Your Model

Inside your custom répertoire du module, create a new répertoire called Model. C'est where your classe de modèle will reside. The path should look like this: app/code/MyCompany/CustomModule/Model.
Maintenant, create your classe de modèle in this répertoire. The class should extend the Magento\Framework\Model\AbstractModel class:

// app/code/MyCompany/CustomModule/Model/MyModel.php

namespace MyCompany\CustomModule\Model;

use Magento\Framework\Model\AbstractModel;

class MyModel extends AbstractModel
{
    protected function _construct()
    {
        $this->_init('MyCompany\CustomModule\Model\ResourceModel\MyModel');
    }
}

  • Step 3: Create db_schema.xml

Inside your custom répertoire du module, create a new répertoire called etc. C'est where you'll define the db_schema.xml fichier. The path devrait être: app/code/MyCompany/CustomModule/etc.
Maintenant, create the db_schema.xml fichier inside the etc répertoire. Ce fichier will define the structure of your table de base de données. Here's an exemple:


<!-- app/code/MyCompany/CustomModule/etc/db_schema.xml -->

<?xml version="1.0" ?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="my_table_name" comment="My Custom Table">
        <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
        <column xsi:type="text" name="description" nullable="true" comment="Description"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="entity_id"/>
        </constraint>
    </table>
</schema>

Replace 'my_table_name' with the actual name you want to use for your table.

  • Step 4: Run the Database Upgrade

Now that you've defined your schéma de base de données using db_schema.xml, you need to run the setup mise à jour to create the table in the database. Run les éléments suivants command from your Magento 2 project root répertoire:


php bin/magento setup:upgrade

Cette commande will execute the schéma de base de données changes defined in your db_schema.xml fichier.

  • Step 5: Interact with Your Model and Table

With your model and table in place, you can now interact with them in your custom extension. Vous pouvez use injection de dépendances to inject your model into other parts of your extension and perform CRUD (Create, Read, Update, Delete) operations on your custom table.

Conclusion


Creating a new model with its associated table de base de données in Magento 2 is a valuable skill for e-commerce développeurs and experts. It vous permet de manage and retrieve data efficiently while adhering to bonnes pratiques in Magento 2 development.

With this knowledge, you can take your Magento 2 personnalisation and extension development to the next level, enhancing the capabilities of your online store.

Happy coding in Magento 2!