3.3.3: The resource model

The resource model

Magento's Object Relational Mapping (ORM) layer requires us to create a few model classes that will work together to automatically map database CRUD operations to an entity object.

The golden triad of classes includes:

  • The entity or data model itself, a transport object representing an instance of the entity
  • The resource model, responsible for the SQL operations that hydrate or consume entity model instances
  • The collection model, responsible for the SQL operations related to sets of multiple models

For each member of the model triad, there is a Magento class that we should extend. The classes dedicated to the Block entity in the Magento_Cms module provides a good "vanilla" example when you need to remind yourself of the proper classes to extend.

We'll implement our resource model first. Create the file for SwiftOtter\OrderExport\Model\ResourceModel\OrderExportDetails. The contents are short and simple: A _construct method (that's a single underscore, not the native PHP constructor!) that calls _init with the name of our database table and the primary key field.

class OrderExportDetails extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    protected function _construct()
    {
        $this->_init('sales_order_export', 'id');
    }
}

That's it! The "automagic" that the resource model inherits can now take care of simple fetching or saving of our entity, needing only these details.

By no means does a resource model have to be this small. Remember that the purpose of a resource model is to encapsulate logic that's specific to the DB storage implementation. So whenever you do have to craft more complex SQL queries for your needs, the resource model (or collection model) should encapsulate that code, with public entry points exposing that functionality.

SEE THE CODE

Complete and Continue