如何在Magento 2中获得客户收藏

Customer Collection为商店管理员提供各种好处。但最显着的优势是它允许您按属性过滤所有商店的客户。因此,在本教程中,我将指导您如何在Magento 2中获取客户收集

如何获得客户收藏

  • 第1步:获取客户对象
  • 第2步:获取客户详细信息

第1步:获取客户对象

Magento 2提供了各种方法来帮助您获取对象,例如从工厂,存储库,对象管理器或直接注入它。您可以使用任何您喜欢的方法,但在使用对象管理器之前应该仔细考虑,尽管很简单,但不是最好的方法。

下面是可用于注入客户工厂和客户对象的行代码。

class MyClass 
{
    protected $_customer;
    protected $_customerFactory;

    public function __construct(...
                                \Magento\Customer\Model\CustomerFactory $customerFactory,
                                \Magento\Customer\Model\Customer $customers
    )
    {
        ...
        $this->_customerFactory = $customerFactory;
        $this->_customer = $customers;
    }

    public function getCustomerCollection() {
        return $this->_customer->getCollection()
               ->addAttributeToSelect("*")
               ->load();
    }

    public function getFilteredCustomerCollection() {
        return $this->_customerFactory->create()->getCollection()
                ->addAttributeToSelect("*")
                ->addAttributeToFilter("firstname", array("eq" => "Max"))
                -load();
    }
}

尽管注入客户对象和客户工厂都是毫无意义的,但是在注入其他对象时,这将是一个很好的演示。

使用第一种方法getCustomerCollection(),将包含所有属性的所有客户的已加载集合将返回。但是,如果由于内存限制而导致属性过多,则使用此方法不是一个理想的选择。

要从给定的客户工厂获取对象,getFilteredCustomerCollection()应用第二种方法。使用此方法,您只需添加create(),您还可以添加过滤器来过滤您的集合。此时,您将收到所有具有名字的客户的集合,例如Max。

第2步:获取客户详细信息

为了获得客户的详细信息,您将需要他们的ID,因为客户需要通过客户ID加载。

为了便于遵循,假设客户ID为10.您将通过运行以下命令获取cutomer详细信息:

$customerID = 10;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Customer')
->load($customerID);
$customerEmail = $customerObj->getEmail();

结论

总之,在Magento 2中获取客户集合并不是一项复杂的任务。它可以在你自己的类的每个构造方法中完成,例如块,控制器,帮助器,模型等。最后,如果你改变依赖注入,不要忘记setup:di:compile否则你可能会得到错误:PHP Fatal error: Uncaught TypeError: Argument 1 passed to

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论