I have a product comparison and am exporting product variants.
Now I would like to load the productNumber
of the products parent and tried the following:
{{ product.parent.productNumber }}
I get the following error message:
It is not possible to read the parent association directly. Please read the parents via a separate call over the repository
Is it somehow possible to read the parent by product.parentId
.
Unfortunately, Shopware will not allow you to add a parent
association and read the product's parent this way. There are several ways to achieve what you need though.
You can use the answer provided by David and have a custom field for the parent product number.
You can plug into an appropriate event (be it ProductPageLoadedEvent
, ProductListingResultEvent
, product.loaded
, something else, or a custom event altogether)
In the subscriber you can simply do
$parentId = $product->getParentId();
$criteria = new Criteria([$parentId]);
$parent = $this->productRepository->search($criteria, $event->getContext())->first();
$product->addExtension('parent', $parent);
This may get tricky when you are listening to the product.loaded
event because it will trigger another one, but you can, for example, add a custom state to the context to alleviate the issue.
In addition, if you're trying to load parent data for multiple products at the same time remember about batching the requests to the database (so as not to query the DB 50 times if you need 50 parents).
You can use this solution
You can also implement a Twig Extension, similar to searchMedia
, which would enable you to search for a product (in this case parent by parentId) in the twig template.