如何通过客户ID获取客户地址?


9

如何通过客户ID获取客户地址/账单地址?到目前为止,这是我所做的:

$customerId = $_POST["customer_id"];
$customer = $this->_customerRepository->getById($customerId);
$address = $this->_addressRepository->getByCustomerId($customerId);//error

Answers:


10

您无法根据客户ID检索地址,因此该代码将永远无法使用:

$address = $this->_addressRepository->getByCustomerId($customerId);//error

因为该getByCustomerId方法在服务合同类中不存在。

但是,您可以做的是使用带有以下代码的数据服务合同客户类:

$customerId = $_POST["customer_id"];
$customer = $this->_customerRepository->getById($customerId);
$addresses = $customer->getAddresses();

请注意,这getAddresses将返回的数组Magento\Customer\Api\Data\AddressInterface

如果您需要默认的帐单邮寄地址,可以致电:

$billingAddress = $customer->getDefaultBilling(); 

但是当我使用$customer->getDefaultBilling();它时返回NULL
简单的家伙

@simpleguy,这是因为您要测试的客户可能没有默认的账单地址
拉斐尔(Raphael)在Digital Pianism上

@RaphaelatDigitalPianism它不适用于我。您能不能让男人知道我如何获得这个细节。
Gaurav Agrawal

如何获得addressID?
贾法尔·品哈尔(Jafar Pinjar),

6

要使用.phtml文件中的订单ID获取客户地址

$customerId = 3;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
$customerAddress = array();

foreach ($customerObj->getAddresses() as $address)
{
    $customerAddress[] = $address->toArray();
}

foreach ($customerAddress as $customerAddres) {

    echo $customerAddres['street'];
    echo $customerAddres['city'];
}

1
protected $_address;

public function __construct(
    ...
    \Magento\Customer\Model\Address $address,
    ...     
)
{
    ...
    $this->_address = $address;
    ...
}

在您的功能中使用:

$addressObj = $this->_address;
$addressObj->load($addressid); 

您可以获得以下地址收集:

$addresses = $addressObj->getCollection();

0

$ private $ customerFactory;

public function __construct(
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    Context $context
) {
    parent::__construct($context);
    $this->customerFactory = $customerFactory;
}

public function execute()
{
    $customerId = 1;
    $customer = $this->customerFactory->create();
    echo "<pre>";
    var_dump($customer->getAddressCollection()->addFieldToFilter('parent_id',$customerId)->getData());
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.