Skip to content

using event sales_order_save_after add data in the table

I hava created an observer with this event file.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_save_after">
        <observer name="purchase_sales_order_place_after" instance="MaxselPurchaseOrderObserverSalesOrderSaveAfter" />
    </event>
</config>

and this is the observer file

* @var LoggerInterface
     */
    protected $logger;

    /**
     * @param ResourceConnection $resourceConnection
     * @param LoggerInterface $logger
     */
    public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @inheritDoc
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        /**
         * Function for the observer for the table
         */
        try {
            $order = $observer->getEvent()->getOrder();
            $orderId = $order->getEntityId();

            // Fetch data from sales_order_grid using SQL query
            $connection = $this->resourceConnection->getConnection();
            $select = $connection->select()

                ->from($this->resourceConnection->getTableName('sales_order_grid'))
                ->where('entity_id = ?', $orderId);

            $orderGridData = $connection->fetchRow($select);
            if ($orderGridData) {
                // Insert data into custom table using SQL query
                $customTable = $this->resourceConnection->getTableName('purchase_order_sales_order_grid');
                $connection->insert($customTable, $orderGridData);
            }
        } catch (LocalizedException $e) {
            $this->logger->error($e->getMessage());
        } catch (Exception $e) {
            $this->logger->critical($e);
        }
        return $this;

Now after the order placed, I faced the row of the sale_order grid and insert in my custom table as custom table also have the same columns in the table.

BUT i want to get the all values of teh sales_order_grid table and insert in my cutom table not using query.

Please help me to get out of this.