ARTICLE

Magento 2 Models, Resource Models, and Collections: How the ORM Loads, Saves, and Filters Data

Magento 2 Models, Resource Models, and Collections: How the ORM Loads, Saves, and Filters Data

Magento 2 splits database access into three classes. A model holds one row’s data and business logic. A resource model runs the SQL that loads, saves, and deletes that row. A collection loads many rows at once with filters, sorting, and paging. You create models and collections through factories, and repositories sit on top as the public API.

Every custom table you add to Magento needs this trio, and most performance problems in custom modules come from using it carelessly: loading a full collection to count it, loading models one at a time inside a loop, or reading thousands of rows into memory. This guide shows the minimum code for each class, what happens when you load and save, and how to use collections without hurting the store.

The three classes and what each is for

Adobe’s overview of the persistence layer describes the design as an active record pattern, where each model object holds a resource model that maps it to one or more database rows. It assigns CRUD operations and their SQL to resource models, and describes a collection as loading multiple models into an array like structure based on a set of rules, similar to a SQL WHERE clause.

Class Extends Responsibility Knows about SQL
Model Magento\Framework\Model\AbstractModel Data for one record, getters and setters, business rules No
Resource model Magento\Framework\Model\ResourceModel\Db\AbstractDb Load, save, delete for one record, plus custom queries Yes
Collection Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection Load many records with filters, order, and paging Yes
Repository Your own class behind an Api interface Stable public API for other modules and the web API No, it delegates

The split matters for a practical reason. If SQL only ever appears in resource models and collections, you can change a table, add an index, or fix a slow query in one place.

The minimum code

Assume a table acme_note with columns note_id, order_id, text, and created_at, created with declarative schema as described in our guide to db_schema.xml.

The model:

<?php
declare(strict_types=1);

namespace Acme\Notes\Model;

use Magento\Framework\Model\AbstractModel;

class Note extends AbstractModel
{
    protected $_eventPrefix = 'acme_note';

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

The resource model:

<?php
declare(strict_types=1);

namespace Acme\Notes\Model\ResourceModel;

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

class Note extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('acme_note', 'note_id');
    }
}

The collection:

<?php
declare(strict_types=1);

namespace Acme\Notes\Model\ResourceModel\Note;

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

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

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

Note the single underscore _construct(). It is a Magento hook called by the real constructor, so you can initialize the class without redeclaring the full constructor signature.

The folder layout is a convention the framework relies on: Model/Note.php, Model/ResourceModel/Note.php, and Model/ResourceModel/Note/Collection.php.

Loading, saving, and deleting one record

Models are data objects, so never inject one directly. Inject its factory and the resource model:

$note = $this->noteFactory->create();
$this->noteResource->load($note, $noteId);

if (!$note->getId()) {
    throw new \Magento\Framework\Exception\NoSuchEntityException(__('Note not found.'));
}

$note->setData('text', 'Customer called about delivery');
$this->noteResource->save($note);

$this->noteResource->delete($note);

A few behaviors are worth knowing.

  • Load never throws for a missing row. It returns an empty model. Check getId().
  • load() can use another column. $this->noteResource->load($note, $orderId, 'order_id') loads by a different field. It returns the first match, so only use it on unique columns.
  • Use the resource model, not $model->save(). The load(), save(), and delete() methods on the model itself are deprecated. They still work and you will see them in older code, but calling the resource model is the supported form.
  • Getters and setters are magic. getOrderId() reads the order_id key. They are convenient, but real typed methods on the model make code easier to follow and to analyze.

What save actually does

save() is more than one INSERT or UPDATE.

  1. If the model has no data changes, the write is skipped. The model tracks this, and dataHasChangedFor('text') and getOrigData('text') let you compare against what was loaded.
  2. A transaction starts.
  3. beforeSave() runs on the model and the <event_prefix>_save_before event fires.
  4. The row is inserted when the model has no ID and updated when it has one. isObjectNew() tells you which.
  5. afterSave() runs and <event_prefix>_save_after fires, still inside the transaction.
  6. The transaction commits, and <event_prefix>_save_commit_after fires.

That last event is the one to use for anything that must only happen once the data is really in the database, such as sending a message to a queue or calling an external system. An observer on save_after can run for a save that is later rolled back.

The same pattern exists for load (_load_before, _load_after) and delete (_delete_before, _delete_after, _delete_commit_after). These events only fire if you set $_eventPrefix, which is why it is in the model above. Our comparison of plugins, observers, and preferences covers when an observer on these events is the right choice.

Custom queries belong in the resource model

When you need a query that is not plain CRUD, add a method to the resource model and use the connection:

public function countForOrder(int $orderId): int
{
    $connection = $this->getConnection();
    $select = $connection->select()
        ->from($this->getMainTable(), 'COUNT(*)')
        ->where('order_id = ?', $orderId);

    return (int) $connection->fetchOne($select);
}

Always bind values with the ? placeholder as shown. Never concatenate request input into a query string.

Working with collections

Create a collection through its generated factory, add rules, then iterate:

$collection = $this->collectionFactory->create();
$collection->addFieldToSelect(['note_id', 'text'])
    ->addFieldToFilter('order_id', ['eq' => $orderId])
    ->addFieldToFilter('created_at', ['gteq' => $since])
    ->setOrder('created_at', 'DESC')
    ->setPageSize(20)
    ->setCurPage(1);

foreach ($collection as $note) {
    // $note is a Note model
}

Collections are lazy

Nothing is queried when you create the collection or add filters. The SQL runs the first time you iterate, call getItems(), count(), or getFirstItem(). After that the collection is loaded, and adding another filter has no effect unless you call clear() first. That catches people who pass a collection between methods and filter it after something else has already looped over it.

Filter conditions

Condition SQL Example
eq, neq =, != ['eq' => 5]
gt, lt, gteq, lteq >, <, >=, <= ['gteq' => '2026-01-01']
like, nlike LIKE, NOT LIKE ['like' => '%delivery%']
in, nin IN (...), NOT IN (...) ['in' => [1, 2, 3]]
null, notnull IS NULL, IS NOT NULL ['null' => true]
from and to >= AND <= ['from' => $a, 'to' => $b]
finset FIND_IN_SET ['finset' => 4]

Calling addFieldToFilter() several times joins the conditions with AND. For OR across fields, pass arrays of fields and conditions in the same positions:

$collection->addFieldToFilter(
    ['text', 'order_id'],
    [['like' => '%refund%'], ['eq' => $orderId]]
);

For anything beyond that, getSelect() returns the underlying select object for joins and grouping. Printing (string) $collection->getSelect() shows the exact SQL, which is the fastest way to debug a filter.

Product, category, and customer collections are EAV collections. Adobe notes that EAV models have their attributes spread over a number of tables, so those collections use addAttributeToSelect() and addAttributeToFilter(), which add the joins for you.

The collection mistakes that slow stores down

1. Counting with count(). count($collection) loads every row and builds a model for each, then counts them in PHP. getSize() runs a SELECT COUNT(*) and loads nothing. Use getSize() to check existence or totals. One caveat: on a collection whose select uses GROUP BY, getSize() can return the wrong total, so verify it there.

2. getFirstItem() on an unbounded collection. It loads the entire result set and returns the first element. Call setPageSize(1) first, or it reads the whole table to give you one row.

3. Loading inside a loop. Calling a resource model or repository once per ID is the N+1 problem: one hundred IDs, one hundred queries. Collect the IDs and run one collection with an in filter.

4. Selecting every column. By default a collection selects *. On a wide table, addFieldToSelect() with only what you need reduces memory and transfer.

5. Loading too much into memory. Every row becomes a model object. For exports and batch jobs, page through the collection with setPageSize() and setCurPage() and call clear() between pages, or use getData() when you only need arrays and not models.

6. Filtering on a column with no index. The ORM does not create indexes for you. If you filter or sort on a column regularly, declare an index for it in db_schema.xml.

7. Saving in a loop. Each save() is its own transaction and its own set of events. For bulk writes, use insertMultiple() or insertOnDuplicate() on the connection inside a resource model method.

If a page is slow and you suspect one of these, measure before you change code. Our guide to profiling a slow Magento 2 request shows how to see the query count and the time spent building models.

Where repositories fit

Models, resource models, and collections are the implementation. Other modules should not depend on them. The stable contract is a repository interface in Api with save, getById, getList, delete, and deleteById, returning data interfaces. Inside, the repository uses exactly the classes above: the factory and resource model for single records, and the collection factory with a collection processor for getList. Adobe’s description of the service layer explains why that boundary exists.

The rule of thumb: inside your own module, a collection is fine when you need a query the repository does not offer. From another module, or from an API, go through the repository. Our guide to Magento 2 repositories and SearchCriteriaBuilder covers that side.

Using the ORM on a Hyva storefront

The ORM is identical whatever the theme. What Hyva changes is the discipline about where it is called from. Templates should not create collections. A view model method should run the query, with a page size, and return plain data for the template to render. Because Hyva pages are light on the frontend, a slow collection in a view model shows up clearly in server response time, which makes these mistakes easier to spot and more worth fixing. That is standard practice on builds from our Hyva development services team.

How this compares to other platforms

Direct database access through an ORM is a property of platforms you host and extend in code. Shopware has its own data abstraction layer with entities, repositories, and criteria objects, which fills the same role with different class names. On Shopify and BigCommerce there is no database access at all. Custom data lives in metafields or in your app’s own storage and is reached through APIs. If a project depends on complex custom entities and queries, that difference should inform the platform decision.

Where Bemeir fits

Bemeir is a Brooklyn agency that builds and supports Magento and Adobe Commerce stores. Custom entities, and the review that keeps their queries fast, are everyday work in our Magento development services. Read more about Bemeir or see our technology partners.

FAQ

What is the difference between a model and a resource model in Magento 2?

The model holds the data and business logic for one record and contains no SQL. The resource model performs the database operations for that record: load, save, delete, and any custom queries. The model is linked to its resource model in _construct() with _init().

What is a collection in Magento 2?

A collection is a class that loads many records of one model type from the database. You add filters, sorting, and paging, and the query runs when you first iterate it. Each item in the result is a model instance.

Should I use getSize() or count() on a collection?

Use getSize() when you only need the number of rows. It runs a COUNT query without loading anything. count() loads the full collection into memory first. On collections that use GROUP BY, check that getSize() returns the expected total.

Should I use a repository or a collection?

Use the repository from other modules, from web APIs, and wherever one exists for the entity. Use a collection inside your own module when you need a query the repository does not provide. The repository is the stable contract. The collection is an implementation detail.

Why does my model’s save() not write anything?

The resource model skips the write when the model reports no data changes. If you set the same values that were loaded, nothing is saved. It can also mean the model was loaded without an ID and you are saving a new, empty object, so check getId() after loading.

Let us help you get started on a project with Magento 2 Models, Resource Models, and Collections: How the ORM Loads, Saves, and Filters Data and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.