0

this is how i used to get an Id from a model:

 /** @var \Top\ExampleModule\Model\example $object */

 $object = $this->modelFactory->create()->load(1,'custom_field');

$object->getId()

I am aware that the load method of the model will be deprecated.

I understand that the correct way to load is to use the Resource Model. My issue however is that the resourceModel does not have getData() or getId() methods.

How then can I get the Id of the instantiated model if there is no $this->getId() method.

This is how I now call it:

/** @var \Top\ExampleModule\Model\example $object */
$model = $this->modelFactory->create();
$object =  $this->viewResource->load($model, $id,'custom_field');

$object->getId()

2 Answers 2

1

Loading model data using $model->load(1, 'custom_field') and $modelResource->load($model, 1, 'custom_field') has the same effect, except that $model->load() will trigger the model_load_before and model_load_after events.

So basically the code you have written will work.

/** @var \Top\ExampleModule\Model\example $object */
$model = $this->modelFactory->create();

// here $id is null, because there are no data populated to the model
$id = $model->getId();

// this will populate the $model with data
$this->viewResource->load($model, $id,'custom_field');

// here $id is set, because the data has been populated to the model by the resource model
$id = $model->getId();
1
  • that is brilliant. i now understand. thanks Rendy
    – theSeeker
    Oct 29, 2020 at 12:17
0

I understand that the correct way to load is to use the Resource Model

That's wrong. The correct way is to use the service contracts, which are implemented with repository interfaces/classes.

For example, to load a product by SKU or ID, you would use Magento\Catalog\Api\ProductRepositoryInterface with methods get() and getById().

To load one or more products by any other attribute, you would use its method getList().

2
  • Is that the only correct way nowadays? Even if I don't want to expose my entity due be module's internal use only? Example: I need to save an external shipping label link once Magento only accept image. It gonna be used only when user click print shipping label in admin.
    – jefferson
    Nov 9, 2021 at 21:33
  • You can always opt for a different structure in your own module, but this is still the recommended way: devdocs.magento.com/guides/v2.4/extension-dev-guide/… Nov 10, 2021 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.