Exploring Magento 2.2 UI Component – Part 2

Exploring Magento 2.2 UI Component – Part 2 Creating Model, Resource Model and Collection classes

In our Last Tutorial Exploring Magento 2.2 UI Component – Part 1 we have created a custom database table, now we will create the appropriate MODEL, RESOURCE MODEL and Collection Classes to fetch the data from our custom table

Step 1:- Lets create our model class. The Model Class defines the entity we are storing and retrieving from database.

In the above code the constant CACHE_TAG denotes our custom table name which we created in the last tutorial. The _construct method in turn calls the _init method with the RESOURCE Model as argument. The RESOURCE Model class is actually responsible for fetching the data from custom table

Step 2:- Once the Model class is created the next step would be to create the RESOURCE Model class.

Resource Model class extends from the base class \Magento\Framework\Model\ResourceModel\Db\AbstractDb. The _construct method calls an _init method. In the _init Method call the first argument represents our custom table name, the second argument represents the PRIMARY KEY of our custom table in our case it is entity_id

Step 3:- In the Last step of our tutorial we will create the Collection class. The Collection is used to fetch the list of models i.e a collection is actually a collection of model objects. In the collection class _construct we will pass the Model class name, Resource Model class name as arguments.