Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 42 ยท Data and the Database

Models, Resource Models and Collections

Understand Magento's three-class data pattern. A model holds data, a resource model talks to the table, a collection loads many rows lazily. Includes runnable stand-ins.

Laravel developers meet one class per table, the Eloquent model, which both holds the data and knows how to save itself. Magento 2 splits that job in three. A model holds the data of one row. A resource model knows how to read and write that row in a particular table. A collection loads many rows and turns them into models. If you create a new custom entity, you usually write all three, plus an etc/db_schema.xml entry for the table (Declarative Schema).

This lesson shows the three classes, the one-line _init calls that connect them, how field names map to columns, how load and save really work today, and when collections hit the database. The Magento classes are read-only. The stand-ins are a small model, resource model and collection on SQLite that follow the same shape. They are teaching tools, not the real framework.

The three classes

flowchart LR
    M["Model<br/>(data of one row)"] -->|"_init(ResourceModel)"| R["Resource model<br/>(table + id column, SQL)"]
    C["Collection<br/>(many rows)"] -->|"_init(Model, ResourceModel)"| M
    C --> R
    R --> DB[("Table")]

The model never writes SQL. The resource model does. The collection builds many models and uses the resource model's table.

Here are the real classes for the acme_note table. They are read-only.

PHP
<?php
// Acme/Note/Model/Note.php
namespace Acme\Note\Model;

use Magento\Framework\Model\AbstractModel;

class Note extends AbstractModel
{
    protected function _construct(): void
    {
        $this->_init(\Acme\Note\Model\ResourceModel\Note::class);
    }
}
PHP
<?php
// Acme/Note/Model/ResourceModel/Note.php
namespace Acme\Note\Model\ResourceModel;

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

class Note extends AbstractDb
{
    protected function _construct(): void
    {
        $this->_init('acme_note', 'note_id'); // table name, primary key column
    }
}
PHP
<?php
// Acme/Note/Model/ResourceModel/Note/Collection.php
namespace Acme\Note\Model\ResourceModel\Note;

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

class Collection extends AbstractCollection
{
    protected $_idFieldName = 'note_id';

    protected function _construct(): void
    {
        $this->_init(
            \Acme\Note\Model\Note::class,
            \Acme\Note\Model\ResourceModel\Note::class
        );
    }
}

Each class has an overridden _construct() (single underscore: it is not PHP's __construct, which the parent classes use for constructor injection). The _init calls are the whole configuration: the model names its resource model, the resource model names its table and primary key, and the collection names both the model class it builds and the resource model that tells it the table.

Data in the model

AbstractModel stores its data in an internal array. You read and write it with getData('title') and setData('title', 'Hello'), or with magic methods: getTitle() and setTitle('Hello') work even though no such methods exist. They are handled by __call, which converts the camel-case method name to a snake_case key (getCreatedAt() reads the created_at key). The primary key has the shortcuts getId() and setId(), which map to the key you passed to _init in the resource model.

Two consequences matter in practice:

  • A typo in a magic method does not fail. getTtile() quietly returns null. Typed getters in a data interface avoid this, which is one reason for Service Contracts and Repositories.
  • The field-to-column mapping is by name. The key created_at is written to the column created_at. There is no separate mapping layer, so an extra key you setData() on a model that is not a column makes the save fail or be ignored, depending on the situation. The resource model reads the real columns of the table and only saves those.

Loading and saving

The resource model does the work. The recommended way to load and save a model is to hand it to the resource model:

PHP
// read-only: the current way, inside a class that received these through its constructor
$note = $this->noteFactory->create();
$this->noteResource->load($note, 42);              // SELECT ... WHERE note_id = 42
$note->setTitle('Updated title');
$this->noteResource->save($note);                  // UPDATE (or INSERT when there is no id)
$this->noteResource->delete($note);                // DELETE

The older calls $note->load(42), $note->save() and $note->delete() still exist on AbstractModel but have been deprecated for a long time, because they put persistence back into the data class and hide the resource model dependency. Prefer a repository for anything beyond a quick internal use. The noteFactory is an auto-generated factory (Factories, Proxies and Generated Code); you never new a model.

During save, the resource model decides between insert and update by checking whether the model has an ID. Around the SQL it fires events (model_save_before, model_save_after, and ones prefixed with the model's $_eventPrefix, such as acme_note_save_after), which is how observers can react to a save. It also records which fields changed, so unchanged saves are cheap.

The stand-in: model and resource model

The first stand-in uses the same split. Model keeps data and offers getData, setData and snake-case magic methods. ResourceModel carries a table and an ID column and does the SQL. Notice that Model itself never touches the database. All output is deterministic.

PHP Stand-in: model and resource model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that a typo in a magic getter returns NULL instead of failing, exactly as in Magento. The log shows insert-or-update decided by the presence of an ID.

Collections: many rows, loaded lazily

A collection wraps a SELECT. You build the query with methods like addFieldToFilter, setOrder and setPageSize, and nothing runs until something needs the rows: iterating with foreach, calling getItems() or getFirstItem(), or load() itself. This is lazy loading. The collection then runs the query once, builds one model per row and keeps them.

PHP
// read-only: a collection used through a factory
$collection = $this->collectionFactory->create();
$collection->addFieldToFilter('priority', ['gteq' => 3])   // WHERE priority >= 3
           ->setOrder('created_at', 'DESC')
           ->setPageSize(20);

foreach ($collection as $note) {          // the query runs here, once
    echo $note->getTitle();
}
$total = $collection->getSize();           // a separate COUNT query, ignoring page size

The filter syntax gets its own lesson (Collections, Filters and SearchCriteria). For now, remember the performance rules that follow from the pattern:

  • Calling getSize() and iterating are two queries. That is normal, but do not call getSize() in a loop.
  • Loading a collection to count it is wasteful. Use getSize(), not count($collection->getItems()).
  • Do not load a model per row inside a loop (the N+1 problem). Add a join or a second collection and map the results (Performance and Security).
  • A collection holds every row it loaded in memory as a full model object. Page large sets with setPageSize() and setCurPage().

The second stand-in adds a collection to the first idea. Look at how the SQL log stays empty while the query is being configured and only gets an entry when the loop starts.

PHP Stand-in: a lazy collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The collection ran one query no matter how often it was read. The real AbstractCollection also has getSize() for a separate COUNT query, clear() to force a reload, and getSelect() for direct access to the underlying query builder, which you should use sparingly.

Choosing the right level

Task Use
Load one entity by ID in your own code the resource model (or better, a repository)
Save a new or changed entity the resource model's save, or a repository
Show a list or loop over many rows a collection, with filters and paging
Expose an entity to other modules or the API a service contract and repository
A one-off report or heavy join a collection with joins, or a direct query through the connection

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which class is responsible for the SQL that reads and writes one row?

    The model holds data. The resource model knows the table and primary key and does the SELECT, INSERT, UPDATE and DELETE.
  2. 2. What does _init() in a resource model's _construct() define?

    The resource model's _init takes the table and the id column. The model's _init names the resource model, and the collection's _init names the model and resource model.
  3. 3. When does a collection run its SELECT?

    Collections are lazy. Filters and ordering only configure the query; loading happens on first use, once.
  4. 4. What happens when you call $note->getTtile() (a typo) on a model?

    Magic getters map the name to a data key, and a missing key is simply null. Typed getters in data interfaces avoid this class of bug.
  5. 5. Which way of persisting a model is current best practice for new code?

    Saving through a model has been deprecated for many releases. The resource model (or a repository built on it) is the supported path.

Summary

  • A Magento entity is three classes: a model (data), a resource model (table and SQL) and a collection (many rows), connected by _init.
  • Model data lives in an array; getX()/setX() are magic methods that map camelCase to snake_case keys, and a typo returns null.
  • Load and save through the resource model (or a repository); $model->save() is deprecated.
  • Collections are lazy: they build a query and run it once, on first use.
  • Count with getSize(), page large sets, and avoid loading a model inside a loop.

Next: Collections, Filters and SearchCriteria