QueryBuilder example

if (\is_array($assignmentFilter)) {
            $this->addAssignmentFilter($query$assignmentFilter);
        }

        $ids = $query->executeQuery()->fetchFirstColumn();

        return new FilteredTagIdsStruct($ids$this->getTotal($query));
    }

    private function getIdsQuery(Criteria $criteria, Context $context): QueryBuilder
    {
        $query = new QueryBuilder($this->connection);

        $query = $this->criteriaQueryBuilder->build($query$this->tagDefinition, $criteria$context);

        /** @var array<string> $select */
        $select = array_merge(['LOWER(HEX(`tag`.`id`))']$query->getQueryPart('select'));
        $query->select($select);
        $query->addGroupBy('`tag`.`id`');
        $query->setMaxResults($criteria->getLimit());
        $query->setFirstResult($criteria->getOffset() ?? 0);

        return $query;
    }
// Early resolve terms to extract score queries         if ($clone->getTerm()) {
            $pattern = $this->interpreter->interpret((string) $criteria->getTerm());
            $queries = $this->scoreBuilder->buildScoreQueries($pattern$definition$definition->getEntityName()$context);
            $clone->addQuery(...$queries);
            $clone->setTerm(null);
        }

        $scoreCriteria = clone $clone;
        $clone->resetQueries();

        $query = new QueryBuilder($this->connection);

        // If an aggregation is to be created on a to many association that is already stored as a filter.         // The association is therefore referenced twice in the query and would have to be created as a sub-join in each case.         // But since only the filters are considered, the association is referenced only once.         // In this case we add the aggregation field as path to the criteria builder and the join group builder will consider this path for the sub-join logic         $paths = array_filter([$this->findToManyPath($aggregation$definition)]);

        $query = $this->criteriaQueryBuilder->build($query$definition$clone$context$paths);
        $query->resetQueryPart('orderBy');

        if ($criteria->getTitle()) {
            
$paginator = new Paginator($query);
        $paginator->setUseOutputWalkers(false);

        return $paginator;
    }

    /** * @return QueryBuilder */
    public function createQueryBuilder()
    {
        return new QueryBuilder($this$this->operatorValidator);
    }

    /** * @return ValidatorInterface */
    public function getValidator()
    {
        return Shopware()->Container()->get(ValidatorInterface::class);
    }

    /** * @param object $object * * @return ConstraintViolationListInterface */

        throw new DecorationPatternException(self::class);
    }

    /** * @return ResolvedSeoUrl */
    public function resolve(string $languageId, string $salesChannelId, string $pathInfo): array
    {
        $seoPathInfo = ltrim($pathInfo, '/');

        $query = (new QueryBuilder($this->connection))
            ->select('id', 'path_info pathInfo', 'is_canonical isCanonical', 'sales_channel_id salesChannelId')
            ->from('seo_url')
            ->where('language_id = :language_id')
            ->andWhere('(sales_channel_id = :sales_channel_id OR sales_channel_id IS NULL)')
            ->andWhere('seo_path_info = :seoPath')
            ->setParameter('language_id', Uuid::fromHexToBytes($languageId))
            ->setParameter('sales_channel_id', Uuid::fromHexToBytes($salesChannelId))
            ->setParameter('seoPath', $seoPathInfo);

        $query->setTitle('seo-url::resolve');

        
 {
    }

    public function search(EntityDefinition $definition, Criteria $criteria, Context $context): IdSearchResult
    {
        if ($criteria->getLimit() === 0) {
            return new IdSearchResult(0, []$criteria$context);
        }

        $table = $definition->getEntityName();

        $query = new QueryBuilder($this->connection);

        $fields = [];
        foreach ($definition->getFields() as $field) {
            if (!$field instanceof StorageAware || $field instanceof ReferenceVersionField || $field instanceof VersionField) {
                continue;
            }
            if ($field instanceof NumberRangeField) {
                $fields[$field->getStorageName()] = $field;

                continue;
            }
            


    public function testFieldResolverThrowsOnNotTranslatedEntities(): void
    {
        $resolver = $this->getContainer()->get(TranslationFieldResolver::class);
        $context = new FieldResolverContext(
            '',
            '',
            new TranslatedField(''),
            $this->getContainer()->get(ProductManufacturerTranslationDefinition::class),
            $this->getContainer()->get(ProductManufacturerTranslationDefinition::class),
            new QueryBuilder($this->getContainer()->get(Connection::class)),
            Context::createDefaultContext(),
            null
        );

        $this->expectException(\RuntimeException::class);
        $resolver->join($context);
    }

    public function testFieldResolverReturnsOnNotTranslatedFields(): void
    {
        $resolver = $this->getContainer()->get(TranslationFieldResolver::class);
        
$builder = $this->getContainer()->get(CriteriaQueryBuilder::class);
        $builder->build($queryMock$productDefinition$criteria, Context::createDefaultContext());
    }

    public function testSortByScoreAndAdditionalSorting(): void
    {
        $productDefinition = $this->getContainer()->get(ProductDefinition::class);
        $criteria = new Criteria();
        $criteria->setTerm('searchTerm');
        $criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));

        $queryBuilder = new QueryBuilder($this->createMock(Connection::class));

        $builder = $this->getContainer()->get(CriteriaQueryBuilder::class);
        $builder->build($queryBuilder$productDefinition$criteria, Context::createDefaultContext());

        static::assertEquals($queryBuilder->getQueryPart('orderBy')[
            'MIN(`product`.`created_at`) ASC',
            '_score DESC',
        ]);
    }

    public function testSortByScoreAndAdditionalSortingWithScore(): void
    {
/** * @throws RuntimeException * @throws InvalidArgumentException */
    protected function joinSalePrices(QueryBuilder $query, ShopContextInterface $context, Criteria $criteria)
    {
        if ($query->hasState(self::VARIANT_LISTING_PRICE_JOINED)) {
            return;
        }

        $subQuery = new QueryBuilder($this->connection);
        $subQuery->from('s_articles_details', 'variant');

        $variantCondition = [
            'listing_price.product_id = variant.articleId',
        ];

        $variantOnSaleCondition = [
            'onsale_listing_price.product_id = variant.articleId',
        ];

        $conditions = $criteria->getConditionsByClass(VariantCondition::class);

        
return $matches;
    }

    /** * @param array<string, array{normal: list<string>, reversed: list<string>}> $tokenSlops * * @return list<list<string>> */
    private function fetchKeywords(Context $context, array $tokenSlops): array
    {
        $query = new QueryBuilder($this->connection);
        $query->select('keyword');
        $query->from('product_keyword_dictionary');

        $query->setTitle('search::detect-keywords');

        $counter = 0;
        $wheres = [];
        $index = 0;

        foreach ($tokenSlops as $slops) {
            $slopsWheres = [];
            
/** * Constructs a sub query that returns the version of the entity requested in the context. IF that version DOES NOT * exist, the live version is returned instead. */
    private function createSubVersionQuery(
        AssociationField $field,
        Context $context,
        EntityDefinitionQueryHelper $queryHelper
    ): QueryBuilder {
        $subRoot = $field->getReferenceDefinition()->getEntityName();

        $versionQuery = new QueryBuilder($this->connection);
        $versionQuery->select(EntityDefinitionQueryHelper::escape($subRoot) . '.*');
        $versionQuery->from(
            EntityDefinitionQueryHelper::escape($subRoot),
            EntityDefinitionQueryHelper::escape($subRoot),
        );
        $queryHelper->joinVersion($versionQuery$field->getReferenceDefinition()$subRoot$context);

        return $versionQuery;
    }

    private function getReferenceColumn(AssociationField $field, Context $context): string
    {
$this->addConditions($criteria$query$context);

        return $query;
    }

    /** * {@inheritdoc} */
    public function createQueryBuilder()
    {
        return new QueryBuilder($this->connection);
    }

    private function addConditions(Criteria $criteria, QueryBuilder $query, ShopContextInterface $context)
    {
        foreach ($criteria->getConditions() as $condition) {
            $handler = $this->getConditionHandler($condition);
            $handler->generateCondition($condition$query$context);
        }
    }

    private function addSorting(Criteria $criteria, QueryBuilder $query, ShopContextInterface $context)
    {


    private function getTranslationQuery(
        EntityDefinition $definition,
        EntityDefinition $translationDefinition,
        string $on,
        Context $context,
        ?string $versionFieldName = null,
    ): QueryBuilder {
        $table = $definition->getEntityName() . '_translation';

        $query = new QueryBuilder($this->connection);

        $select = $this->getSelectTemplate($translationDefinition);

        // first language has to be the "from" part, in this case we have to use the system language to enforce we have a record         $chain = array_reverse($context->getLanguageIdChain());

        $first = array_shift($chain);
        $firstAlias = $on . '.translation';

        $foreignKey = EntityDefinitionQueryHelper::escape($firstAlias) . '.' . $definition->getEntityName() . '_id';

        
$connection = $this->createMock(Connection::class);
        $connection->expects(static::once())->method('fetchAssociative')->willReturn($fetchDataResult);

        if ($fetchDataResult === false) {
            $connection->expects(static::never())->method('createQueryBuilder');
        }

        if ($fetchParentLanguageResult !== false) {
            $result = $this->createMock(Result::class);
            $result->expects(static::once())->method('fetchOne')->willReturn($fetchParentLanguageResult);
            $connection->expects(static::once())->method('executeQuery')->willReturn($result);
            $connection->expects(static::atMost(1))->method('createQueryBuilder')->willReturn(new QueryBuilder($connection));
        } else {
            $result = $this->createMock(Result::class);
            $result->expects(static::atMost(1))->method('fetchOne')->willReturn(false);
            $connection->expects(static::atMost(1))->method('executeQuery')->willReturn($result);
            $connection->expects(static::atMost(1))->method('createQueryBuilder')->willReturn(new QueryBuilder($connection));
        }

        $factory = new BaseContextFactory(
            $salesChannelRepository,
            $currencyRepository,
            $customerGroupRepository,
            
array $ids,
        EntityDefinition $root,
        AssociationField $association,
        string $class,
        Context $context,
        bool $restrictDeleteOnlyFirstLevel = false
    ): array {
        if (empty($ids)) {
            return [];
        }

        $query = new QueryBuilder($this->connection);
        $query->from(
            EntityDefinitionQueryHelper::escape($root->getEntityName()),
            EntityDefinitionQueryHelper::escape($root->getEntityName())
        );

        $this->queryHelper->resolveField($association$root$root->getEntityName()$query$context);

        $alias = $root->getEntityName() . '.' . $association->getPropertyName();

        if ($association instanceof ManyToManyAssociationField) {
            $alias .= '.mapping';
        }
/** * @param array<string, mixed> $partial * * @return list<array<string, mixed>> */
    private function fetch(Criteria $criteria, EntityDefinition $definition, Context $context, FieldCollection $fields, array $partial = []): array
    {
        $table = $definition->getEntityName();

        $query = $this->criteriaQueryBuilder->build(
            new QueryBuilder($this->connection),
            $definition,
            $criteria,
            $context
        );

        $this->joinBasic($definition$context$table$query$fields$criteria$partial);

        if (!empty($criteria->getIds())) {
            $this->queryHelper->addIdCondition($criteria$definition$query);
        }

        
Home | Imprint | This part of the site doesn't use cookies.