Magento 2 Models

In Magento 2, Models are PHP classes used to interact with the database using Magento’s built-in ORM (Object Relational Mapping). Models are part of the MVC architecture and work closely with ResourceModel and Collection classes.

📁 Types of Models in Magento 2

  • Model: Holds data and business logic
  • ResourceModel: Handles actual database operations
  • Collection: Loads multiple rows from a table

🧾 Step 1: Create a Database Table

Create a custom table using a Setup/InstallSchema.php or db_schema.xml (recommended for Magento 2.4+).

📦 Step 2: Create Model Class

// Model/Post.php
namespace Bcn\Blog\Model;

use Magento\Framework\Model\AbstractModel;

class Post extends AbstractModel
{
    protected function _construct()
    {
        $this->_init(\Bcn\Blog\Model\ResourceModel\Post::class);
    }
}
  

🗄️ Step 3: Create ResourceModel

// Model/ResourceModel/Post.php
namespace Bcn\Blog\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Post extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('bcn_blog_post', 'post_id'); // table name, primary key
    }
}
  

📚 Step 4: Create Collection Class

// Model/ResourceModel/Post/Collection.php
namespace Bcn\Blog\Model\ResourceModel\Post;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
            \Bcn\Blog\Model\Post::class,
            \Bcn\Blog\Model\ResourceModel\Post::class
        );
    }
}
  

⚙️ Step 5: Use Model in Controller or Block

$post = $this->postFactory->create();
$post->setTitle('Hello World');
$post->save();
  

✅ Summary

  • Magento models follow an ORM pattern
  • Model handles business logic
  • ResourceModel defines table & primary key
  • Collection loads multiple rows

This structure allows Magento 2 to manage data efficiently and cleanly. Now you’re ready to explore how Blocks and Views use these Models in the frontend or admin panel.