Magento 2: How to get Customer collection filter by Full name like admin grid?
-
05-05-2021 - |
解决方案
First, you have to call the Customer Collection factory and after that add addNameToSelect()
function to that collection.
namespace {nameSpace};
class CustomCollection
{
protected $collectionFactory;
public function __construct(
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collectionFactory
)
{
$this->collectionFactory = $collectionFactory;
}
public function getCustomCollectionWithFullName()
{
$customerName = 'John';
$customerCollection = $this->collectionFactory->create();
$customerCollection->addAttributeToSelect('*'); // use * for all field
$customerCollection->addNameToSelect();
// for == condition
$customerCollection->getSelect() ->where(
'name = ?',
$customerName
);
// where like %V%
// $customerCollection->where('name LIKE ?', '%' . $customerName . '%');
}
}
其他提示
I found a way that works better(at least for me) and is based on the answer of Amit.
Just in a similar fashion, here is the code to include attributes for the collection:
$resultingCustomers = $this->customerCollectionFactory->create();
$resultingCustomers->addAttributeToSelect('*');
$resultingCustomers->addNameToSelect();
The difference is that instead of injecting an SQL WHERE
clause into the collection like the answer of Amit, i used addAttributeToFilter
:
$resultingCustomers->addAttributeToFilter('name',['like'=>($keyword . '%')]);
It works very well on Magento 2.4 and it is probably "The Magento Way" of doing it because you dont rely on low level SQL statements.
The final code snippet for this is below:
public function filterCustomersByFullname($keyword){
$resultingCustomers = $this->customerCollectionFactory->create();
$resultingCustomers->addAttributeToSelect('*');
$resultingCustomers->addNameToSelect();
$resultingCustomers->addAttributeToFilter('name',['like'=>($keyword . '%')]);
return $resultingCustomers;
}