Question

I am trying to assign a guest order to a specific customer programmatically.

I have loaded the collection of orders placed by the guest users using following code:

public function __construct(
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory    $orderCollectionFactory,
) {
    $this->orderCollectionFactory = $orderCollectionFactory;
}

public function getGuestOrderCollection()
{
    $orderCollecion = $this->orderCollectionFactory
        ->create()
        ->addFieldToSelect('*');

    $orderCollecion->addAttributeToFilter('customer_is_guest', ['eq'=>1]);
    foreach($orderCollecion as $orderData){
        if($orderData->getCustomerId()){
            $order->setCustomerId($orderData->getCustomerId());
            $order->setCustomerIsGuest(0);
            $this->orderRepository->save($orderData);
            $message = "DONE";
        } else {
            $message = "Fail";
        }
    }
    return $message;
}

It doesn't work. It's not saving the order to that customer.

Not getting any error though.

What am I doing wrong? Any help would be greatly appreciated.

Was it helpful?

Solution

Note that your code doesn't make a lot of sense to me. An order that was saved as a guest order should not have a customer_id set. Is your code passing into the if($orderData->getCustomerId()) block at all?

Also, do note that your returned $message variable will currently only be set for the last order in the collection.

That said, it looks like you are trying to save $order, while you should actually be using $orderData, like so:

public function __construct(
  \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
) {
  $this->orderCollectionFactory = $orderCollectionFactory;
}

public function getGuestOrderCollection() {

  $orderCollecion = $this->orderCollectionFactory
    ->create()
    ->addFieldToSelect('*');

  $orderCollecion->addAttributeToFilter('customer_is_guest', ['eq'=>1]);
  foreach($orderCollecion as $orderData){

    if($orderData->getCustomerId()) {
      $orderData->setCustomerId($orderData->getCustomerId());
      $orderData->setCustomerIsGuest(0);
      $orderData->save($orderData);
      $message = "DONE";
    } else{  
      $message = "Fail";
    }

  return $message;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top