如何使用observer在Magento 2的customer_entity表中保存自定义字段值

时间:2017-01-18 10:08:41

标签: php magento2 observers

以下是我的观察员代码:

<?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

2 个答案:

答案 0 :(得分:0)

尝试从模型中加载客户

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

答案 1 :(得分:0)

尝试使用resourceModel来使用客户数据更改进行保存,而不是使用模型进行保存

$customerResourceModel->save($customer);