ORM¶
- Means by which data is persisted from objects to a relational database
- Magento's ORM is built around models, resource models and resource collections
- Models: Data and behaviour
- Resource Models: Maps data for storage
- Collections: Groups of models, as well as filtering, sorting and paging
- Resources: Database connection adapters
Models¶
- Models only can manpulate data
- Models don't concern themselves with data persistence
- Models'
load(),save(),delete()methods are deprecated
- Models'
- Persisted Models must extend
Magento\Framework\Model\AbstractModel- In the
_construct()method, a link to the Resource Model class is specified with$this->_init('Namespaced\Path\To\ResourceModel')
- In the
Resource Models¶
- Resource Model contains the primary ID field name
- The resource models' CRUD methods should be used to persist models
- Resource Models extend
Magento\Framework\Db\Adapter\Pdo, which extendsZend\Db
- In the
_construct()method, a link to the main table is specified with$this->_init('table_name', 'primary_key_column');
Collections¶
- Implement
Magento\Framework\Model\Resource\Db\Collection\AbstractCollection - In the
_construct()method, a link to the Model and Resource Model is specified with$this->_init('Namespaced\Path\To\Model', 'Namespaced\Path\To\ResourceModel'); - Provide methods
addFieldToFilter()getConnection()getSelect()addBindParam()getIdFieldName()distinct()addOrder()setOrder()unshiftOrder()getItems()getSize()getSelectCountSql()load()resetData()walk()
- Records are lazy-loaded, the first time a list is accessed
- Query operator maps
eq==neq=!=like=likenlike=not likein=innin=not innotnull=is NOT NULLnull=is NULLgt=>lt=<gteq=>=moreq=>=lteq=<=finset=find_in_setfrom, to=>= and <=
CRUD Workflow¶
Loading Models¶
$resourceModel->load($modelId, $field = null)- A third parameter allows for loading by a non-ID attribute
- EAV models should use
loadByAttribute()instead
- Models'
_beforeLoad()method fires amodel_load_beforegenerically, and also specifically for the model - Models'
_afterLoad()method fires amodel_load_aftergenerically, and also specifically for the model - Useful methods
save()isDeleted()hasDataChangesvalidateBeforeSave()isSaveAllowed()afterCommitCallback()
Install and Upgrade Scripts¶
- Install scripts run once per module
- Upgrade scripts are run after subsequent updates
- Module version is set in (module)etc/module.xml root node's
setup_versionattribute - Versions are stored in the
setup_moduletable - Installers implement
Magento\Framework\Setup\Install(Data|Schema)Interface'sinstall()method - Upgraders implement
Magento\Framework\Setup\Upgrade(Data|Schema)Interface'supgrade()method - Should start with
$installer = $setup; $installer->startSetup();and end with$installer->endSetup(); - Scripts are run only when
bin/magento setup:upgradeis run
Making changes¶
- Raw SQL as a parameter to the
run()method $installer->getConnection()containsnewTable()createTable()addConstraint()dropTable()
EAV¶
- EAV aims to make data storage across multiple website more flexible
- Means the data is stored across multiple tables
- Means values and attributes can be decoupled from their entities
- Data types
- Meta information: entity type, attributes per entity type, attribute set and groups
- Content: entity records, attribute values
Tables¶
eav_entity_typecontainsentity_type_identity_type_codeentity_tabledefault_attribute_set_idincrement_model
eav_attributecontainsattribute_identity_type_idattribute_codebackend_typebackend_modelsource_modelfrontend_model
(entity_type)_entitycontainsentity_identity_type_id- Any
staticattribute type values
(entity_type)_(backend_type)(int,decimal,varchar,text,datetime) containsvalue_identity_type_identity_idattribute_idvalue
EAV Loading and Saving¶
- Like flat table entities, EAV models extend
Magento\Framework\Model\AbstractModel - EAV Resource Models however extend
Magento\Eav\Entity\AbstractEntity Magento\Eav\Entity\AbstractEntityprovidesgetAttribute()for getting an attribute by code or IDsaveAttribute()saves only that value, rather than the full entitygetWriteConnection()getEntityTable()
- Flat entities are loaded
$model->load()$resourceModel->load()- (Resource table)
- (Model table)
- EAV entities are loaded
$model->load()$resourceModel->load()eav_entity_typeandeav_attrbute- (EAV Attributes table)
- (Attribute values tables)
- (Attributes and Values)
Collections¶
- EAV Collections have a few methods:
addAttributeToSelect()adds the attribute values table to the select and the value to the resultaddAttributeToFilter()joins the attribute table to the join and allows filteringjoinAttribute()joins a value table from another entity's attribute
Attribute Management¶
-
Attribute columns include:
attribute_identity_type_id: for the entity type IDattribute_code: A unique, human readable nameattribute_model: Optional model. Unspecified defaults toMagento\Eav\Model\Entity\Attributebackend_model: Optional backend model. Unspecified defaults toMagento\Eav\Model\Entity\Attribute\Backendbackend_type: One ofstatic,varchar,datetime,int,text,decimalbackend_table: Optional override for the value tablefrontend_model: Alternative frontend model. Unspecified defaults toMagento\Eav\Model\Entity\Attribute\Frontend\DefaultFrontendfrontend_input: Input type for the adminfrontend_label: Default label for the adminfrontend_class: CSS class name for inputsis_required: client-side validation, and validated on importdefault_value: displayed if no value is specified
-
Setup scripts use
Magento\Eav\Setup\EavSetup, providing:addAttribute($entityType, $attributeCode, $dataArray)updateAttribute($entityType, $attributeCode, $field, $value)- Fields are mapped using
Magento\Eav\Model\Entity\Setup\PropertyMapperInterface::map()
Config Classes¶
Magento\Eav\Model\ConfigprovidesgetAttribute($entityType, $attributeCode)returns an attribute instancegetEntityType($entityTypeCode)returns an entity type instance
Attribute Models¶
- Extend
Magento\Eav\Model\Entity\Attribute\(Type)\Abstract(Type)- Where
Typeis one ofFrontend,Backend,Source - Frontend provides
setAttribute($attribute)getAttribute()getInputType()getLabel()getLocalizedLabel()getValue(\Magento\Framework\DataObject $object)isVisible()getClass()getConfigField($fieldName)getOption($optionId)getInputRendererClass()
- Backend provides
setAttribute($attribute)getAttribute()getType()isStatic()getTable()getEntityIdField()setValueId($valueId)setEntityValueId($entity, $valueId)getValueId()getEntityValueId($entity)getDefaultValue()validate($object)- Multiple before- and after load and save
- Where
Magento\Eav\Model\Entity\Attribute\BackendHooks for save, load and deleteArrayBackendDateTimeDefaultBackendIncrementSerializedStoreTime\CreatedTime\Updated
Sourcefor select/multiselect attribute typesBooleanConfigStoreTable
FrontendDateTimeDefaultFrontend