0

How can I load the Customer Model and Collection by Extension Attribute in Magento 2?

I've declared an extension attribute in extension_attributes.xml and saved to the Customer Model. Now, How can I load the Customer Model and Collection by the Extension Attribute?

<extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
    <attribute code="building_name" type="string"/>
</extension_attributes>
0

I don't think we can load the customer by extension attribute, but we can use the Customer Collection to fetch the customer by attribute. This is an example of how to use customer collection to fetch users by attribute.

<?php

namespace <Namespace>\<Module_Name>\Model;

class Customer
{
    /**
     * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory
     */
    private $customerCollectionFactory;

    /**
     * Customer constructor.
     *
     * @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory
     */
    public function __construct(
        \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory
    ) {
        $this->customerCollectionFactory = $customerCollectionFactory;
    }

    /**
     * @param $attributeCode
     * @param $value
     *
     * @return \Magento\Framework\DataObject[]
     */
    public function loadCustomerByAttribute($attributeCode, $value)
    {
        return $this->customerCollectionFactory->create()->addFieldToFilter($attributeCode, $value)->getItems();
    }

    public function execute(){
        $customers = $this->loadCustomerByAttribute('building_name', 'Test');
    }
}

I hope that it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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