簡體   English   中英

如何使用觀察者在 Magento 2 的 customer_entity 表中保存自定義字段值

[英]How can i save custom field value in customer_entity table in Magento 2 using observer

以下是我的觀察者代碼:

<?php

class CustomerOrderCountObserver implements ObserverInterface
{

    /**
     * @var customerFactory
     */
    private $customerFactory;

    /**
     * 
     * @param CustomerFactory $customerFactory
     */
    public function __construct(
        CustomerFactory $customerFactory
    ) {
          $this->customerFactory = $customerFactory;
    }

    /**
     * Upgrade customer password hash when customer has logged in
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $orderInstance = $observer->getEvent()->getdata();
        $orderIds = $observer->getEvent()->getdata('order_ids');
        $orderCount = is_array($orderIds)?count($orderIds):0;
        $orderId = current($orderIds);
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $session = $objectManager->get('Magento\Customer\Model\Session');

        if($session->isLoggedIn()) {
            $customer = $this->customerFactory->create()->load($session->getCustomerId());
            $orderCount = $orderCount + $customer->getOrderCount();
            $customer->setOrderCount($orderCount);
            $customer->save($customer);
        } 
    }
}

我不知道我做錯了什么。 它不保存客戶列值order_count

嘗試使用 resourceModel 保存客戶數據更改,而不是使用模型保存

$customerResourceModel->save($customer);

嘗試從模型加載客戶

 $customer = Mage::getModel('customer/customer')->load($session->getCustomerId());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM