3

I have a custom varchar attribute stored on customers. I've been struggling to find the proper way to query for a specific attribute value without going straight to SQL joins. What is the right way to query a custom attribute from a model?

e.g. customer a has "my_attribute" value of "3aF"

How do I query the customer model / collection to find the user based on that value?

1 Answer 1

5

You can use the customer repository located at app/code/Magento/Customer/Model/ResourceModel/CustomerRepository.php (having API \Magento\Customer\Api\CustomerRepositoryInterface) like:

/**
 * @var \Magento\Customer\Api\CustomerRepositoryInterface
 */
protected $customerRepository;

/**
 * @var \Magento\Framework\Api\SearchCriteriaInterface
 */
protected $searchCriteria;

/**
 * @var \Magento\Framework\Api\Search\FilterGroup
 */
protected $filterGroup;

/**
 * @var \Magento\Framework\Api\FilterBuilder
 */
protected $filterBuilder;

/**
 * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
 * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
 * @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
 * @param \Magento\Framework\Api\FilterBuilder $filterBuilder
 */
public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
    \Magento\Framework\Api\SearchCriteriaInterface $criteria,
    \Magento\Framework\Api\Search\FilterGroup $filterGroup,
    \Magento\Framework\Api\FilterBuilder $filterBuilder
) {
    $this->customerRepository = $customerRepository;
    $this->searchCriteria = $criteria;
    $this->filterGroup = $filterGroup;
    $this->filterBuilder = $filterBuilder;
    $customers = $this->searchCustomersByAttributeValue('my_attribute', '3aF');
}

public function searchCustomersByAttributeValue($attributeCode, $value)
{
    $this->filterGroup->setFilters(
        [
            $this->filterBuilder
                ->setField($attributeCode)
                ->setConditionType('eq')
                ->setValue($value)
                ->create()
        ]
    );

    $this->searchCriteria->setFilterGroups([$this->filterGroup]);
    $customersList = $this->customerRepository->getList($this->searchCriteria);
    $customers = $customersList->getItems();

    return $customers;
}

As a result you have the list of the matched customers:

result

Here (in dev docs) you can find some other filter types.

2
  • works perfecfly, but instead of using the model directly \Magento\Customer\Model\ResourceModel\CustomerRepository one should always use their repository interface. \Magento\Customer\Api\CustomerRepositoryInterface Commented Nov 2, 2018 at 8:18
  • @ZeeshanKhuwaja right, I'll change my answer asap Commented Nov 2, 2018 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.