How to add sales order status history data programmatically in Magento 2?

To add sales order status history records to the given order, you required order id, status, comment message, is customer notify and entity name to insert entry on the sales_order_status_history table.

Create a factory object for the class Magento\Sales\Model\Order\Status\History and save the object data using the Order Status History Repository Interface.

I hope you have all the needed data to create an entry for the sales_order_status_history table for an order.

namespace Jesadiya\AddOrderStatusHistory\Model;

use Magento\Sales\Api\Data\OrderStatusHistoryInterface;
use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface;
use Magento\Sales\Model\Order\Status\HistoryFactory;
use Psr\Log\LoggerInterface;

class OrderStatusHistory
     * @var HistoryFactory
    private $historyFactory;

     * @var OrderStatusHistoryRepositoryInterface
    private $historyRepository;

     * @var LoggerInterface
    private $logger;

    public function __construct(
        HistoryFactory $historyFactory,
        OrderStatusHistoryRepositoryInterface $historyRepository,
        LoggerInterface $logger
    ) {
        $this->historyFactory = $historyFactory;
        $this->historyRepository = $historyRepository;
        $this->logger = $logger;

     * add sales order status history data
     * @param int $orderId
     * @return void
    public function addCommentToOrder(int $orderId): void
        /** @var OrderStatusHistoryInterface $history */
        $history = $this->historyFactory->create();
        $message = 'Your custom message for the order';
        $status = 'pending';
        try {
        } catch (Exception $exception) {

In the above method, all the required field is self-explanatory. You can add any status for the comment, boolean value for the customer notify and parent id is the order main id.

Once the code runs successful, New Entry inserted to the table with the given order.

You can Add Status History Comment to the order by Order id in Magento 2.