Magento 2 - 在结账时通过送货地址获取客户地址ID

问题描述 投票:0回答:2

我在获取客户地址ID时遇到问题,因为它返回空值。

这是我尝试过的:

$checkout = $this->_sessionCheckout->getQuote();
if ($checkout) {
   $shippingAddress = $checkout->getShippingAddress();
   if ($shippingAddress) {
       $addressId = $shippingAddress->getCustomerAddressId();
       $this->_logger->log(100, print_r('address Id: ' . $addressId , true)); //Returns null 
       /** @var \Magento\Customer\Api\Data\AddressInterface $address */
       $address = $this->_addressRepository->getById($addressId);
       $address->setCity($city_name);
       $this->_addressRepository->save($address);
}

我只需要获取客户地址ID即可更新城市。我不知道为什么它返回一个空值。

先感谢您。


编辑细节:

下图显示了已保存的送货地址:

shipping-addresses

我想知道的是如何知道每个送货地址的客户地址ID。所以我可以修改我想要的任何细节。

magento2 shipping street-address magento2.2 customer
2个回答
0
投票

当您以访客用户的身份下订单时,您必须在结帐页面上添加送货地址,此时将不会有客户参考对象,因此您将客户地址ID的值变为null。

当您作为注册客户下订单时,您应该有默认送货地址,然后只有您可以获得客户地址ID的值。

发生这种情况是因为customer_address_id是对customer_address表和customer_address表引用customer_entity表的引用。


0
投票

您可以按如下方式获取订单如果您想要调用此信息,请在构造函数中添加以下内容(如果尚未使用)。

protected $checkoutSession;
public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Psr\Log\LoggerInterface $logger
    )
    {

        $this->checkoutSession = $checkoutSession;
        $this->logger = $logger;
    }


    $order = $session->getLastRealOrder();
    $orderdata = $order->getData();
    $shipping_address_id = $orderdata['shipping_address_ID'];

此地址是在结账流程的付款阶段选择的最终送货地址。

© www.soinside.com 2019 - 2024. All rights reserved.