Search code examples
shopwareshopware6

How to get prices with ProductEntity?


I created my own Entity called "MyProductEntity" (and also Definition/Collection) which has a relation to some Product (eg. a product is linked with another product)

The problem is that MyProductEntity->connectedProduct doesn't contain prices (eg. calculatedPrices). Does anyone know how to load the prices? I read somewhere that I should use SalesChannelProductEntity instead of ProductEntity? But I am not sure how? Any hints?

Here are (I hope) the relevant parts from my code:

class MyProductEntity extends Entity
{
    protected string $productId;
    protected string $productVersionId;
    protected ProductEntity $product;

    protected string $connectedProductId;
    protected string $connectedProductVersionId;
    protected ProductEntity $connectedProduct;
    //I tried to use here "SalesChannelProductEntity" instead of "ProductEntity"
    //...
    //other properties
}

in some subscriber: (eg.: for ProductPageLoadedEvent::class) I load MyProductEntity like this:

public function getMyProducts(ProductPageLoadedEvent $event): array
{

    $page = $event->getPage();
    $salesChannelContext = $event->getSalesChannelContext();
    $product = $page->getProduct();

    $criteria = new Criteria();
    $criteria->addFilter(new EqualsFilter('productId', $product->getId()));
    $criteria->addAssociation('connectedProduct');

    $myProducts = $this->myProductRepository->search($criteria, $salesChannelContext);
    //$this->myProductRepository = defined via services.xml / in constructor:
    // EntityRepository $myProductRepository
}

Solution

  • As you already found out the field calculatedPrices and similar are exclusive to the SalesChannelProductDefinition and SalesChannelProductEntity. You could simply create your own sales channel definition in addition to the regular definition:

    class SalesChannelMyProductDefinition extends MyProductDefinition implements SalesChannelDefinitionInterface
    
    <service id="Foo\MyPlugin\SalesChannel\SalesChannelMyProductDefinition">
        <tag name="shopware.sales_channel.entity.definition"/>
    </service>
    

    Then use the repository of your new sales channel definition:

    $myProduct = $this->getContainer()->get('sales_channel.my_product.repository')
        ->search($criteria, $salesChannelContext)->first();
    // should then be an instance of SalesChannelProductEntity
    $salesChannelProduct = $myproduct->getConnectedProduct();