Question

I need to assign a Guest Order to a Customer, so i found this link

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

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);
 ...

From the above two solutions For 1st solution (SQL)

  1. Where should I write SQL query so that it updates the tables sales_order and sales_order_grid before my myaccount phtml loads so that guest orders will be displayed.
  2. How can I get ORDER ID for guest checkout order as I need to update the sales_order table for guest order entity id.

    I tried this code

     public  function  getOrderId() {
      $order = $this->_checkoutSession->getLastRealOrder();
      $orderId=$order->getEntityId();
      return $orderId;
    }
    

    But this doesnt give any order id. Altough I am able to get customer id.

For 2nd solution (PHP)

  1. I am not able to get order id (entity_id).

How can I resolve these issues.

Was it helpful?

Solution

With your PHP variant you can get the order Id, you just have to replace $order->getEntityId(); with $order->getId(); which is the correct method to get the entity id of the order.

This code should work for you:

public  function  getOrderId() {
  $orderIncrementId = $this->_checkoutSession->getLastRealOrderId();
  //load the order by Increment Id depending on the context of your script, for example like this
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $order = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($orderIncrementId);
  $orderId=$order->getId();
  return $orderId;
}

It may also be possible that your order entity is already stored in session:

    $this->_checkoutSession->getLastOrderId();`
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top