Load Model by custom database field in Magento 2
This is a simple tutorial showing how to load a model using a custom field rather than loading by the primary key. There are several situations the primary key isn’t the only unique field and we may have other fields in the table which are unique and are used more often to load the model. To name a few, Customer entity has email as the unique field and the Product entity has SKU. These fields are used quite often to load a single database row into the model.
This tutorial will show you how to do that for an existing or custom model.
Load using collection:
class {YourClassName}
{
private $customModelFactory;
...
public function __construct(
...
\{Vendor}\{ModuleName}\Model\CustomModelFactory $customModelFactory,
...
) {
...
$this->customModelFactory = $customModelFactory;
...
}
public function yourMethod()
{
...
$customModel = $this->customModelFactory->create()
->getCollection()
->addFieldToFilter('{your_field_name}', '{your_field_value}');
...
}
}
Using the load method in the resource model:
class {YourClassName}
{
private $customModelFactory;
...
public function __construct(
...
\{Vendor}\{ModuleName}\Model\CustomModelFactory $customModelFactory,
...
) {
...
$this->customModelFactory = $customModelFactory;
...
}
public function yourMethod()
{
...
$customModel = $this->customModelFactory->create();
$customModel->getResource()->load($customModel, '{your_field_value}', '{your_field_name}');
...
}
}
Replace everything that is wrapped
within {...}
with your own values.