根据邮件用户名获取顾客对象时,可以用Customer模块自带的loadByEmail方法。

public function loadByEmail($customerEmail)
    {
        $this->_getResource()->loadByEmail($this, $customerEmail);
        return $this;
    }

但是直接使用下面的方法

$customer = Mage::getModel('customer/customer')
                ->loadByEmail($email);

会报错,错误信息如下:

Customer website ID must be specified when using the website

事实上,创建customer对象时需要指定websitId

正确的使用方法如下:

$customer = Mage::getModel('customer/customer')
                ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
                ->loadByEmail($email);

补充:为什么必须指定 websiteId

客户数据在 Magento 1 里是按 Website 隔离的:同一个邮箱可以在不同 website 下注册成两个独立账号(比如国内站和国际站共用一套系统)。loadByEmail() 最终拼出来的 SQL 条件里带着 website_id = ?,拿不到 websiteId 就无法确定要加载哪一个。

// 报错路径:loadByEmail() 内部拿到的是 null
WHERE customer.email = 'a@b.com' AND customer.website_id = NULL

// 正确路径:先 setWebsiteId 再 loadByEmail
WHERE customer.email = 'a@b.com' AND customer.website_id = 1

Mage::app()->getStore()->getWebsiteId() 取的是当前请求所在门店的 website。如果这里跑在后台或者 CRON 里,getStore() 可能不是前台门店,取到的 websiteId 就不对,这时应当显式传入目标 website:

$websiteId = Mage::getModel('core/website')->load('base', 'code')->getId();
$customer  = Mage::getModel('customer/customer')
    ->setWebsiteId($websiteId)
    ->loadByEmail($email);

if (!$customer->getId()) {
    // 查不到时 getId() 为 null,别直接拿空对象去做后续操作
}

本文整理于 2016 年,代码基于 Magento 1.x。