Question

I'm trying to grab the oldest customer, using the customer repository from the database.

Here's my code so far:

    // if custom is active 
    $isActivefilter = $this->filter
        ->setField('is_active')
        ->setConditionType('eq')
        ->setValue(1)
        ->create(); 

    $isActiveFilterGroup = $this->filterGroup
        ->addFilter($isActivefilter)
        ->create();

    // ========== AND ========== //

    // if customer has an account id = $user
    $accountIdFilter = $this->filter
        ->setField('account_id')
        ->setConditionType('eq')
        ->setValue($user)
        ->create(); 

    $accountIdFilterGroup = $this->filterGroup
        ->addFilter($accountIdFilter)
        ->create();

    // ========== SORT BY CREATED AT ========== // 

    // setting the sort order to ascending will bring the oldest records to the top 
    $sortByCreatedAt = $this->sortOrder
        ->setAscendingDirection()
        ->create();

    $searchCriteria = $this->searchCriteria
        ->setFilterGroups([$isActiveFilterGroup, $accountIdFilterGroup])
        ->setSortOrders([$sortByCreatedAt]);

So before I set the search criteria in getList($searchCriteria), I want to make sure I'm only querying for one result like limit 1

Is there a way to do that using the repository and search criteria?

Was it helpful?

Solution

Figured it out.

http://devdocs.magento.com/guides/v2.2/extension-dev-guide/searching-with-repositories.html

$searchCriteria = $this->searchCriteria
        ->setFilterGroups([$accountIdFilterGroup])
        ->setSortOrders([$sortByCreatedAt])
        ->setPageSize(1);

->setPageSize() limits the amount of entities in the query.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top