Load model using custom field in Magento 2

0
5217
Load model using custom field in Magento 2
Load model using custom field in Magento 2

Beside loading model using primary ID field, we can also load model using custom field in Magento 2. I will show you how to do that in this post.

In any version prior to Magento 2.3, you can load model using custom field through model class, or model factory class, which is:

$model = $modelFactory->create()->load('value', 'field_name');

For example:

$marketingDepartment = $departmentFactory->create()->load('Marketing', 'department_code');

$itDepartment = $departmentFactory->create()->load('IT', 'department_code');

But it has been marked as deprecated in recent versions since Magento 2.3.

Instead, you can use resource model class to load model using custom field.

So the above code will look like following:

$model = $modelFactory->create();
$resourceModel->load($model, 'value', 'field_name');

// For example:

$marketingDepartment = $departmentFactory->create();
$departmentResource->load($marketingDepartment, 'Marketing', 'department_code'); 

$itDepartment = $departmentFactory->create();
$departmentResource->load($itDepartment, 'IT', 'department_code'); 

Certainly, you will need to apply dependency injection to inject appropriate factory and resource model instance before loading models.

If those are to be called multiple times, it is better to create a model repository which encapsulate those function calls. Yes, repository design pattern is the way to go.

Have fun ~