The best (optimized) way to get order id i.e sales_order.entity_id
from increment id by creating a custom DB query in Magento2.
- Create a
GetOrderIdByIncrementId
class:
<?php
declare(strict_types =1);
namespace Adapttive\SalesOrder\Model\Order;
use Exception;
use Magento\Sales\Model\ResourceModel\Order as OrderResource;
/**
* Class GetOrderIdByIncrementId: To get order.entity_id by order.increment_id
* Reference from \Magento\Sales\Model\OrderIncrementIdChecker
*/
class GetOrderIdByIncrementId
{
/**
* @var OrderResource
*/
private $resource;
/**
* @param OrderResource $resource
*/
public function __construct(OrderResource $resource)
{
$this->resource = $resource;
}
/**
* Get order id by order increment id.
*
* @param string|int $incrementId
* @return int
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function get($incrementId): int
{
$result = 0;
try {
/** @var \Magento\Framework\DB\Adapter\AdapterInterface $adapter */
$adapter = $this->resource->getConnection();
$bind = [':increment_id' => $incrementId];
/** @var \Magento\Framework\DB\Select $select */
$select = $adapter->select();
$select->from($this->resource->getMainTable(), $this->resource->getIdFieldName())
->where('increment_id = :increment_id');
$entityId = $adapter->fetchOne($select, $bind);
if ($entityId > 0) {
$result = (int)$entityId;
}
} catch (Exception $e) {
$result = 0;
}
return $result;
}
}
- Usage:
$orderId = $this->getOrderIdByIncrementId->get($orderIncrementId)
Reference: https://adapttive.com/blog/magento-2-get-order-id-by-increment-id/