Question

I have a question regarding link between entities. Consider that a car is linked to a brand. The car entity will have a brand_Id attribute.

Coming from the "Symfony universe", using the Doctrine ORM, the linked entities will be automatically generated and loaded if used.

echo $myCar->getBrand()->getName();

My question is : is there a way to do the same with Magento 2? Until now, I had to inject the linked entity repository and use lazy loading.

public function __construct(
        ...
        BrandRepositoryInterface $brandRepository,  
        ...
) {

    $this->brandRepository = $brandRepository;
    ... 
}

public function getBrand() {
    if($this->brand == null) {
        $this->brand = $this->brandRepository->getById($this->getBrandId());
    }

    return $this->brand;
}

Is there an alternative like in the Doctrine ORM? Or something else, a good MG2 practice for example?

Was it helpful?

Solution

I don't think there is an other way of doing this in Magento (I may be wrong).
Code wise there is an other way, but the principle is the same.
Here is an example in the core.
It'a about the order -> order item relation.
Order is a parent entity for the order item entity.
The method getOrder from the Magento\Sales\Model\Order\Item class looks like this:

public function getOrder()
{
    if ($this->_order === null && ($orderId = $this->getOrderId())) {
        $order = $this->_orderFactory->create();
        $order->load($orderId);
        $this->setOrder($order);
    }
    return $this->_order;
}

This means (you already know what it means but I'm adding it here anyway) that if the _order member is not set, get the order from the database based on the order id.
This example does not use repositories, it calls directly the deprecated method load.
I guess this is because the orders models did not get refactored yet to use repositories.
Anyway, the repository approach is better because the order object is memoized.
Calling this 2 times for 2 different order items that belong to the same order will result in touching the db only once if you use repositories.

Conclusion: You are doing it right (in my opinion).

[Edit]
A similar approach is taken for the order->invoice relation and other relations in the sales module.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top