addAssociations example

 {
    }

    public function readDocument(string $documentId, Context $context, string $deepLinkCode = ''): ?RenderedDocument
    {
        $criteria = new Criteria([$documentId]);

        if ($deepLinkCode !== '') {
            $criteria->addFilter(new EqualsFilter('deepLinkCode', $deepLinkCode));
        }

        $criteria->addAssociations([
            'documentMediaFile',
            'documentType',
        ]);

        /** @var DocumentEntity|null $document */
        $document = $this->documentRepository->search($criteria$context)->get($documentId);

        if (!$document instanceof DocumentEntity) {
            if (Feature::isActive('v6.6.0.0')) {
                throw DocumentException::documentNotFound($documentId);
            }

            
private function __construct()
    {
    }

    /** * @param array<int, string> $ids */
    public static function create(array $ids, string $deepLinkCode = ''): Criteria
    {
        $criteria = new Criteria($ids);

        $criteria->addAssociations([
            'lineItems',
            'transactions.paymentMethod',
            'currency',
            'language.locale',
            'addresses.country',
            'addresses.salutation',
            'addresses.countryState',
            'deliveries.positions',
            'deliveries.shippingMethod',
            'deliveries.shippingOrderAddress.country',
            'deliveries.shippingOrderAddress.countryState',
            
if ($id === null) {
            return null;
        }

        $criteria = new Criteria([$id]);

        return $this->loadOrder($criteria$storableFlow->getContext()$id);
    }

    private function loadOrder(Criteria $criteria, Context $context, string $orderId): ?OrderEntity
    {
        $criteria->addAssociations([
            'orderCustomer',
            'orderCustomer.salutation',
            'lineItems.downloads.media',
            'lineItems.cover',
            'deliveries.shippingMethod',
            'deliveries.shippingOrderAddress.country',
            'deliveries.shippingOrderAddress.countryState',
            'stateMachineState',
            'transactions.stateMachineState',
            'transactions.paymentMethod',
            'deliveries.stateMachineState',
            
'Name',
            'Active',
            'Maintenance',
            'Default Language',
            'Languages',
            'Default Currency',
            'Currencies',
            'Domains',
        ];

        $criteria = new Criteria();
        $criteria->addAssociations(['language', 'languages', 'currency', 'currencies', 'domains']);
        /** @var SalesChannelCollection $salesChannels */
        $salesChannels = $this->salesChannelRepository->search($criteria, Context::createDefaultContext())->getEntities();

        $data = [];
        foreach ($salesChannels as $salesChannel) {
            /** @var LanguageEntity $language */
            $language = $salesChannel->getLanguage();
            /** @var LanguageCollection $languages */
            $languages = $salesChannel->getLanguages();
            /** @var CurrencyEntity $currency */
            $currency = $salesChannel->getCurrency();
            
$progress = $this->import(
            $context,
            ProductDefinition::ENTITY_NAME,
            '/fixtures/products_with_update_by.csv',
            'products_with_update_by.csv',
            $clonedPropertyProfile->getId()
        );

        static::assertImportExportSucceeded($progress$this->getInvalidLogContent($progress->getInvalidRecordsLogId()));

        $products = $this->productRepository->search((new Criteria())->addAssociations(['categories', 'properties'])$context);

        static::assertEquals(1, $products->count());
        static::assertInstanceOf(ProductEntity::class$product = $products->first());
        static::assertInstanceOf(CategoryCollection::class$categories = $product->getCategories());
        static::assertInstanceOf(PropertyGroupOptionCollection::class$properties = $product->getProperties());
        static::assertEquals(3, $categories->count());
        static::assertEquals(3, $properties->count());

        $taxes = $this->getContainer()->get('tax.repository')->search(
            (new Criteria())->addFilter(new EqualsFilter('taxRate', 23)),
            $context
        )
$productRepository->create([$product], Context::createDefaultContext());

        $orderId = Uuid::randomHex();
        $orderData = $this->getOrderData($orderId, Context::createDefaultContext())[0];

        $orderData['lineItems'][0]['productId'] = $productId;

        $this->orderRepository->create([$orderData], Context::createDefaultContext());

        $criteria = new Criteria();

        $criteria->addAssociations([
            'lineItems',
            'billingAddress',
            'deliveries.stateMachineState',
            'deliveries.shippingOrderAddress',
        ]);

        /** @var OrderEntity|null $order */
        $order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();

        static::assertNotNull($order);

        

    protected function getListQuery()
    {
        $customerId = (int) $this->Request()->get('customerId');

        if (!$customerId) {
            throw new \RuntimeException('You have to provide a valid customerId.');
        }

        $query = parent::getListQuery();
        $query = $this->addAssociations($query);
        $query->andWhere('IDENTITY(address.customer) = :customerId')
            ->setParameter('customerId', $customerId);

        return $query;
    }

    /** * {@inheritdoc} */
    protected function getQueryPaginator(QueryBuilder $builder$hydrationMode = AbstractQuery::HYDRATE_ARRAY)
    {
        
public static function isoCodeProvider(): \Generator
    {
        yield 'Polish zloty iso code' => ['PLN'];
        yield 'Euro iso code' => ['EUR'];
        yield 'US dollar iso code' => ['USD'];
        yield 'British pound iso code' => ['GBP'];
    }

    private function createProductExportCriteria(string $id): Criteria
    {
        $criteria = new Criteria([$id]);
        $criteria->addAssociations([
            'salesChannel',
            'salesChannelDomain.language',
        ]);

        return $criteria;
    }

    private function getSalesChannelId(): string
    {
        /** @var EntityRepository $repository */
        $repository = $this->getContainer()->get('sales_channel.repository');

        


    /** * @param array<string, mixed> $result * * @return array{total:int, data:EntityCollection<Entity>} */
    public function globalData(array $result, Context $context): array
    {
        $ids = array_column($result['hits'], 'id');
        $criteria = new Criteria($ids);
        $criteria->addAssociations(['options.group']);

        return [
            'total' => (int) $result['total'],
            'data' => $this->repository->search($criteria$context)->getEntities(),
        ];
    }

    public function globalCriteria(string $term, Search $criteria): Search
    {
        $splitTerms = explode(' ', $term);
        $lastPart = end($splitTerms);

        
public function testCreate(): void
    {
        $builder = (new ProductBuilder($this->ids, 'p1'))
            ->price(10)
            ->category('c1')
            ->manufacturer('m1')
            ->prices('r1', 5);

        $this->productRepository->create([$builder->build()], Context::createDefaultContext());

        $criteria = new Criteria();
        $criteria->addAssociations([
            'manufacturer',
            'prices',
            'categories',
        ]);

        /** @var ProductEntity $product */
        $product = $this->productRepository->search($criteria, Context::createDefaultContext())->first();
        $product->addExtension('test', new LanguageCollection([
            (new LanguageEntity())->assign(['id' => $this->ids->create('l1'), '_entityName' => 'language']),
        ]));
        $events = $this->entityLoadedEventFactory->create([$product], Context::createDefaultContext());

        
$this->logger->error($exceptions->getMessage()['error' => $exceptions]);

            throw $exceptions;
        }

        $this->adjustment->adjust($cart$result$context);
    }

    private function getTaxProviders(SalesChannelContext $context): TaxProviderCollection
    {
        $criteria = (new Criteria())
            ->addAssociations(['availabilityRule', 'app'])
            ->addFilter(
                new AndFilter([
                    new EqualsFilter('active', true),
                    new OrFilter([
                        new EqualsFilter('availabilityRuleId', null),
                        new EqualsAnyFilter('availabilityRuleId', $context->getRuleIds()),
                    ]),
                ])
            );

        /** @var TaxProviderCollection $providers */
        
$criteria->getAssociation('transactions')->addSorting(new FieldSorting('createdAt'));

        /** @var CustomerEntity $customer */
        $customer = $context->getCustomer();

        $criteria->addFilter(
            new EqualsFilter(
                'order.orderCustomer.customerId',
                $customer->getId()
            )
        );
        $criteria->addAssociations([
            'lineItems',
            'deliveries.shippingOrderAddress',
            'deliveries.stateMachineState',
            'orderCustomer',
            'tags',
            'transactions.stateMachineState',
            'stateMachineState',
        ]);

        $this->eventDispatcher->dispatch(new OrderPaymentMethodChangedCriteriaEvent($orderId$criteria$context));

        

            $context->getContext()
        );
    }

    private function getOrder(string $orderId, SalesChannelContext $context): OrderEntity
    {
        /** @var EntityRepository $orderRepository */
        $orderRepository = $this->getContainer()->get('order.repository');
        $criteria = new Criteria([$orderId]);

        $criteria->addAssociations(['stateMachineState', 'transactions.stateMachineState']);

        return $orderRepository->search($criteria$context->getContext())->first();
    }

    private function createCustomPaymentWithRule(SalesChannelContext $context, string $ruleId): string
    {
        $paymentId = Uuid::randomHex();

        $this->getContainer()->get('payment_method.repository')->create([
            [
                'id' => $paymentId,
                

    public function generate(array $ids, string $template, SeoUrlRouteInterface $route, Context $context, SalesChannelEntity $salesChannel): iterable
    {
        $criteria = new Criteria($ids);
        $route->prepareCriteria($criteria$salesChannel);

        $config = $route->getConfig();

        $repository = $this->definitionRegistry->getRepository($config->getDefinition()->getEntityName());

        $associations = $this->getAssociations($template$repository->getDefinition());
        $criteria->addAssociations($associations);

        $criteria->setLimit(50);

        /** @var RepositoryIterator<LandingPageCollection|CategoryCollection|ProductCollection> $iterator */
        $iterator = $context->enableInheritance(static fn (Context $context): RepositoryIterator => new RepositoryIterator($repository$context$criteria));

        $this->setTwigTemplate($config$template);

        while ($entities = $iterator->fetch()) {
            yield from $this->generateUrls($route$config$salesChannel$entities);
        }
    }
SalesChannelContextService::CUSTOMER_ID => $this->createCustomer('Jon', 'Doe')]
        );
    }

    public function testOrderDeliveryStateTransition(): void
    {
        $orderId = $this->performOrder();

        // getting the id of the order delivery         $criteria = new Criteria([$orderId]);

        $criteria->addAssociations([
            'stateMachineState',
            'deliveries.stateMachineState',
            'deliveries.shippingOrderAddress',
        ]);

        /** @var OrderEntity $order */
        $order = $this->orderRepository->search($criteria$this->salesChannelContext->getContext())->first();
        $deliveries = $order->getDeliveries();
        static::assertNotNull($deliveries);
        $delivery = $deliveries->first();
        static::assertNotNull($delivery);
        
Home | Imprint | This part of the site doesn't use cookies.