Magento – How to assign a Guest Order to a Customer – Magento 2

magento2

I've got some order from guest and later they create their account and ask to link the old orders.

How can I do it?

I tried to update the table sales_order but it wasn't enough to work.

Thanks

Best Answer

Using SQL

UPDATE sales_order SET customer_id = {YOUR CUSTOMER ID}, customer_is_guest = 0 where entity_id = {YOUR ORDER ID};
UPDATE sales_order_grid SET customer_id = {YOUR CUSTOMER ID} where entity_id = {YOUR ORDER ID};

Using PHP (if customer exist)

public function __construct(
    .....
    \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
    ...
    $this->orderRepository = $orderRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
}

public function execute()
{
    $incrementId = {YOUR ORDER ID};
    $customerId = {YOUR CUSTOMER ID};

    $searchCriteria = $this->searchCriteriaBuilder->addFilter('increment_id', $incrementId, 'eq')->create();
    $order = $this->orderRepository->getList($searchCriteria)->getFirstItem();

     if ($order->getId() && !$order->getCustomerId()) 
     {
        $order->setCustomerId($customerId);
        $order->setCustomerIsGuest(0);
        $this->orderRepository->save($order);
     ...

Using a Module https://github.com/magepal/magento2-guest-to-customer

Related Topic