Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Last active May 11, 2020 10:17
Show Gist options
  • Save 0-Sony/14da5b5ac4d47b667954b1db723a4ddb to your computer and use it in GitHub Desktop.
Save 0-Sony/14da5b5ac4d47b667954b1db723a4ddb to your computer and use it in GitHub Desktop.
Magento 2 : Filter a collection using search criteria builder
<?php
/**
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Phuong LE <[email protected]>
* @copyright Copyright (c) 2020 Men In Code Ltd (https://www.menincode.com)
*/
namespace Namespace\MyModule\Block
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\View\Element\Template;
class useCriteria extends Template
{
/**
* useCriteria constructor.
* @param CustomerRepositoryInterface $customerRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
CustomerRepositoryInterface $customerRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->customerRepository = $customerRepository
$this->searchCriteriaBuilder = $searchCriteriaBuilder
}
/**
* Return CustomerInterface | null
*/
public function getSpecificCustomer() {
$email = '[email protected]';
$websiteId = 2;
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('email', $email, 'eq')
->addFilter('website_id', $websiteId, 'eq')
->create();
$customerCollection = $this->customerRepository->getList($searchCriteria);
$customer = $customerCollection->getFirstItem();
return !!$customer->getId() !== false ? $customer : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment