Getting order id for guest checkout order
-
18-02-2021 - |
문제
I need to assign a Guest Order to a Customer, so i found this link
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)
- Where should I write SQL query so that it updates the tables
sales_order
andsales_order_grid
before my myaccount phtml loads so that guest orders will be displayed. 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)
- I am not able to get order id (entity_id).
How can I resolve these issues.
해결책
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();`
제휴하지 않습니다 magento.stackexchange