In this post, we will go deeper into the usage of Module and Collection in Magento 2. After this post, you can insert some sample data on the custom database table and display them on frontend. Let’s start!
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
How To Use Model And Collection In Magento 2
1. How To Use Model and
Collection in Magento 2
Provided By Mageworld
A Leading Magento Provider
2. OUTLINE
1. Insert some sample data on the custom
database table
2. Create Model, Resource Model and Collection
files
3. Get data from the database and display them
at the frontend
3. 1. Insert some sample data on the custom
database table
Upgrade Tutorial_SimpleNews module installed in the last tutorial
to insert the sample data.
4. 1. Insert some sample data on the custom
database table
1.1. Create the upgrade data file
Create file: app/code/Tutorial/SimpleNews/Setup/UpgradeData.php
Purpose: check the module version and insert some sample data into
the custom table
=> Go to our blog post to see full source code
5. 1. Insert some sample data on the custom
database table
1.2. Modify the configuration file
Open the configuration file at app/code/Tutorial/SimpleNews/etc/module.xml
Modify setup_version="1.0.0" tosetup_version="1.0.1“
6. 1. Insert some sample data on the custom
database table
Open the Command
in Windows
Go to Magento root
folder
Run this command
line to install module
1.3. Upgrade the module
7. 1. Insert some sample data on the custom
database table
Module to install: binmagento setup:upgrade
The result in the tbl_tutorial_simplenews table:
8. 1. Insert some sample data on the custom
database table
If your module is not installed before:
Create file: app/code/Tutorial/SimpleNews/Setup/InstallData.php
Purpose: insert the sample data into the custom database table
when the module is installed
=> Go to our blog post to see full source code
9. 2. Create Model, Resource Model and
Collection files
Purpose: insert, update, delete and get data in the database.
2.1. Create model file: app/code/Tutorial/SimpleNews/Model/News.php
10. 2. Create Model, Resource Model and
Collection files
2.2. Create resource model file:
app/code/Tutorial/SimpleNews/Model/Resource/News.php
11. 2. Create Model, Resource Model and
Collection files
2.3. Create collection file:
app/code/Tutorial/SimpleNews/Model/Resource/News/Collection.php
12. 3. Get data from the database and display
them at the frontend
3.1. Create route file:
app/code/Tutorial/SimpleNews/etc/frontend/routes.xml
13. 3. Get data from the database and
display them at the frontend
3.2. Create controller file:
app/code/Tutorial/SimpleNews/Controller/Index/Index.php
=> Go to our blog post to see full source code
14. 3. Get data from the database and display
them at the frontend
3.3. Clear the Magento cache then access with URL
http://localhost/magento2/news/