addSorting example

$config = Config::fromLog($this->logEntity);
        $criteriaBuilder = new CriteriaBuilder($this->repository->getDefinition());

        $criteria = $criteria === null ? new Criteria() : clone $criteria;
        $criteriaBuilder->enrichCriteria($config$criteria);

        $enrichEvent = new EnrichExportCriteriaEvent($criteria$this->logEntity);
        $this->eventDispatcher->dispatch($enrichEvent);

        if ($criteria->getSorting() === []) {
            // default sorting             $criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));
        }
        $criteria->addSorting(new FieldSorting('id'));

        $criteria->setOffset($offset);
        $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_EXACT);

        $criteria->setLimit($this->exportLimit <= 0 ? 250 : $this->exportLimit);
        $fullExport = $this->exportLimit <= 0;

        /** @var ImportExportFileEntity $file */
        $file = $this->logEntity->getFile();
        


    /** * {@inheritdoc} */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new ShopwareStyle($input$output);
        $context = Context::createDefaultContext();

        $criteria = new Criteria();
        $criteria->addSorting(new FieldSorting('name', FieldSorting::ASCENDING));
        $filter = $input->getOption('filter');
        if ($filter) {
            $criteria->addFilter(new MultiFilter(
                MultiFilter::CONNECTION_OR,
                [
                    new ContainsFilter('name', $filter),
                    new ContainsFilter('label', $filter),
                ]
            ));
        }
        /** @var PluginCollection $plugins */
        
$categoryId = (int) $element->getConfig()->get('article_slider_category');

        if ($type === self::TYPE_PRODUCT_STREAM) {
            $categoryId = $context->getShop()->getCategory()->getId();
        }

        $criteria = $this->criteriaFactory->createBaseCriteria([$categoryId]$context);
        $criteria->limit($limit);

        switch ($type) {
            case self::TYPE_LOWEST_PRICE:
                $criteria->addSorting(new PriceSorting(SortingInterface::SORT_ASC));
                break;
            case self::TYPE_HIGHEST_PRICE:
                $criteria->addSorting(new PriceSorting(SortingInterface::SORT_DESC));
                break;
            case self::TYPE_TOPSELLER:
                $criteria->addSorting(new PopularitySorting(SortingInterface::SORT_DESC));
                break;
            case self::TYPE_NEWCOMER:
                $criteria->addSorting(new ReleaseDateSorting(SortingInterface::SORT_DESC));
                break;
            case self::TYPE_RANDOM:
                
use Shopware\Bundle\SearchBundleDBAL\QueryBuilder;

class TotalAmountSortingHandler implements SortingHandlerInterface
{
    public function supports(SortingInterface $sorting)
    {
        return $sorting instanceof TotalAmountSorting;
    }

    public function handle(SortingInterface $sorting, QueryBuilder $query)
    {
        $this->addSorting($sorting$query);
    }

    private function addSorting(TotalAmountSorting $sorting, QueryBuilder $query): void
    {
        $query->addOrderBy('customer.invoice_amount_sum', $sorting->getDirection());
    }
}
$isPartial = $partial !== [];

        $propertyAccessor = $this->buildOneToManyPropertyAccessor($definition$association);

        // inject sorting for foreign key, otherwise the internal counter wouldn't work `order by customer_address.customer_id, other_sortings`         $sorting = array_merge(
            [new FieldSorting($propertyAccessor, FieldSorting::ASCENDING)],
            $fieldCriteria->getSorting()
        );

        $fieldCriteria->resetSorting();
        $fieldCriteria->addSorting(...$sorting);

        $ids = array_values($collection->getIds());

        if ($isPartial) {
            // Make sure our collection index will be loaded             $partial[$association->getPropertyName()] = [];
        }

        $isInheritanceAware = $definition->isInheritanceAware() && $context->considerInheritance();

        if ($isInheritanceAware) {
            
        $route->load($ids->get('c.1')new Request()$context$criteria);
    }

    public static function criteriaProvider(): \Generator
    {
        yield 'Paginated criteria' => [(new Criteria())->setOffset(1)->setLimit(20)];
        yield 'Filtered criteria' => [(new Criteria())->addFilter(new EqualsFilter('active', true))];
        yield 'Post filtered criteria' => [(new Criteria())->addPostFilter(new EqualsFilter('active', true))];
        yield 'Aggregation criteria' => [(new Criteria())->addAggregation(new StatsAggregation('price', 'price'))];
        yield 'Query criteria' => [(new Criteria())->addQuery(new ScoreQuery(new EqualsFilter('active', true), 200))];
        yield 'Term criteria' => [(new Criteria())->setTerm('test')];
        yield 'Sorted criteria' => [(new Criteria())->addSorting(new FieldSorting('active'))];
    }

    /** * @dataProvider stateProvider */
    public function testStates(array $current, array $config): void
    {
        $ids = new IdsCollection();

        $criteria = new Criteria();

        

    public function generateSorting(
        SortingInterface $sorting,
        QueryBuilder $query,
        ShopContextInterface $context
    ) {
        if (!$query->hasState(SearchTermConditionHandler::STATE_INCLUDES_RANKING)) {
            return;
        }

        $this->addSorting($sorting$query);
    }

    private function addSorting(SearchRankingSorting $sorting, QueryBuilder $query): void
    {
        $query->addOrderBy('searchTable.ranking', $sorting->getDirection());
    }
}
return $responseStruct->getOrders();
    }

    private function createCriteria(Request $request): Criteria
    {
        $limit = $request->get('limit');
        $limit = $limit ? (int) $limit : 10;
        $page = $request->get('p');
        $page = $page ? (int) $page : 1;

        $criteria = (new Criteria())
            ->addSorting(new FieldSorting('order.createdAt', FieldSorting::DESCENDING))
            ->addAssociation('transactions.paymentMethod')
            ->addAssociation('deliveries.shippingMethod')
            ->addAssociation('orderCustomer.customer')
            ->addAssociation('lineItems')
            ->addAssociation('lineItems.cover')
            ->addAssociation('lineItems.downloads.media')
            ->addAssociation('addresses')
            ->addAssociation('currency')
            ->addAssociation('documents.documentType')
            ->setLimit($limit)
            ->setOffset(($page - 1) * $limit)
            
use Shopware\Bundle\SearchBundleDBAL\QueryBuilder;

class AgeSortingHandler implements SortingHandlerInterface
{
    public function supports(SortingInterface $sorting)
    {
        return $sorting instanceof AgeSorting;
    }

    public function handle(SortingInterface $sorting, QueryBuilder $query)
    {
        $this->addSorting($sorting$query);
    }

    private function addSorting(AgeSorting $sorting, QueryBuilder $query): void
    {
        $query->addOrderBy('customer.age', $sorting->getDirection());
    }
}
static::assertTrue($criteria->hasAssociation('prices'));
        $nested = $criteria->getAssociation('prices');

        static::assertCount(1, $nested->getFilters());
        static::assertCount(1, $nested->getSorting());
    }

    public function testCriteriaToArray(): void
    {
        $criteria = (new Criteria())
            ->addSorting(new FieldSorting('order.createdAt', FieldSorting::DESCENDING))
            ->addSorting(new CountSorting('transactions.id', CountSorting::ASCENDING))
            ->addAssociation('transactions.paymentMethod')
            ->addAssociation('deliveries.shippingMethod')
            ->setLimit(1)
            ->setOffset((1 - 1) * 1)
            ->setTotalCountMode(100);

        $criteria->getAssociation('transaction')->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING));

        $criteriaArray = $this->requestCriteriaBuilder->toArray($criteria);

        

        $criteria = new Criteria([$orderId]);
        $criteria
            ->addAssociation('orderCustomer.customer')
            ->addAssociation('orderCustomer.salutation')
            ->addAssociation('deliveries.shippingMethod')
            ->addAssociation('deliveries.shippingOrderAddress.country')
            ->addAssociation('transactions.paymentMethod.appPaymentMethod.app')
            ->addAssociation('lineItems.cover')
            ->addAssociation('currency')
            ->addAssociation('addresses.country')
            ->getAssociation('transactions')->addSorting(new FieldSorting('createdAt'));

        /** @var OrderEntity|null $order */
        $order = $this->orderRepository->search($criteria$context->getContext())->first();
        static::assertNotNull($order);

        return $order;
    }
}
return $mappings;
    }

    /** * Gather all mapping keys used in all profiles with the same source entity and fill the keyLookupTable. * Keys from newer profiles are prioritized. */
    private function getKeyLookupTable(Context $context, string $sourceEntity): array
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('sourceEntity', $sourceEntity));
        $criteria->addSorting(new FieldSorting('createdAt'));
        $profiles = $this->profileRepository->search($criteria$context)->getEntities();

        $keyLookupTable = [];
        foreach ($profiles as $profile) {
            $mappings = $profile->getMapping();
            if ($mappings !== null) {
                foreach ($mappings as $mapping) {
                    if (!empty($mapping['key']) && !empty($mapping['mappedKey'])) {
                        $keyLookupTable[$mapping['mappedKey']] = $mapping['key'];
                    }
                }
            }
        $route->load(new Request()$criteria$context);
    }

    public static function criteriaProvider(): \Generator
    {
        yield 'Paginated criteria' => [(new Criteria())->setOffset(1)->setLimit(20)];
        yield 'Filtered criteria' => [(new Criteria())->addFilter(new EqualsFilter('active', true))];
        yield 'Post filtered criteria' => [(new Criteria())->addPostFilter(new EqualsFilter('active', true))];
        yield 'Aggregation criteria' => [(new Criteria())->addAggregation(new StatsAggregation('name', 'name'))];
        yield 'Query criteria' => [(new Criteria())->addQuery(new ScoreQuery(new EqualsFilter('active', true), 200))];
        yield 'Term criteria' => [(new Criteria())->setTerm('test')];
        yield 'Sorted criteria' => [(new Criteria())->addSorting(new FieldSorting('active'))];
    }

    /** * @dataProvider invalidationProvider */
    public function testInvalidation(\Closure $before, \Closure $after, int $calls): void
    {
        $this->getContainer()->get('cache.object')
            ->invalidateTags([CachedCountryRoute::buildName(TestDefaults::SALES_CHANNEL)]);

        $route = $this->getContainer()->get(CountryRoute::class);

        


        if ($sorting === 'random') {
            return $this->addRandomSort($criteria);
        }

        if ($sorting) {
            $sorting = explode(':', $sorting);
            $field = $sorting[0];
            $direction = $sorting[1];

            $criteria->addSorting(new FieldSorting($field$direction));
        }

        return $criteria;
    }

    private function addRandomSort(Criteria $criteria): Criteria
    {
        $fields = [
            'id',
            'stock',
            'releaseDate',
            
use Shopware\Bundle\SearchBundleDBAL\QueryBuilder;

class AverageProductAmountSortingHandler implements SortingHandlerInterface
{
    public function supports(SortingInterface $sorting)
    {
        return $sorting instanceof AverageProductAmountSorting;
    }

    public function handle(SortingInterface $sorting, QueryBuilder $query)
    {
        $this->addSorting($sorting$query);
    }

    private function addSorting(AverageProductAmountSorting $sorting, QueryBuilder $query): void
    {
        $query->addOrderBy('customer.product_avg', $sorting->getDirection());
    }
}
Home | Imprint | This part of the site doesn't use cookies.