Magento 2 : Custom Sql

Posted . Visible to the public.

Custom Sqls

To insert records to tracking table, fetch the data from custom table as array

$tableName = $this->connection->getTableName(self::SHIPMENT_TABLE);
        $jointTableName = $this->connection->getTableName(self::TABLE);

        $sql = $this->connection->select()->from(
                ['ss' => $tableName],
                [
                    'parent_id' => 'ss.entity_id',
                    'order_id' => 'ss.order_id'
                ]
            )->joinLeft(
                ['kst' => $jointTableName],
            'ss.increment_id = kst.shipping_id',
                [
                    'track_number' => 'kst.tracking_number',
                    'title' => 'kst.title',
                    'carrier_code' => 'kst.carrier',
                ]

            )->where(
                'ss.increment_id IN (?)',
                $incrementIds
            );

        $result = $this->connection->fetchAll($sql);
        
        if ($result) {
            $shipmentTrackingTableName = $this->connection->getTableName(self::SHIPMENT_TRACKING_TABLE);
            $this->connection->insertOnDuplicate(
                $shipmentTrackingTableName,
                $result,
                ['track_number', 'title', 'carrier_code']);
            return true;
        }

Fetching records

$selectCodes = $this->connection->select()
                ->from($tableName, ['code'])
                ->where('code  IN (?)', $insertCodes)
                ->where('vendor_id != ?', $vendorId);
                
                $invalidCodes = $this->connection->fetchCol($selectCodes);

fetching a single column

$sqlToFetchParentId =  $this->connection->select()
            ->from($tableName)
            ->columns(['entity_id'])
            ->where(
                'increment_id IN (?)',
                $incrementIds
            );
        $parentIdColumn = $this->connection->fetchCol($sqlToFetchParentId);

deleting records

$this->connection->delete($shipmentTrackingTableName, ['parent_id  IN (?)' => $parentIdColumn]);

updating table

$tableName = $this->connection->getTableName(self::SHIPMENT_TABLE);
        $this->connection
            ->update($tableName, ['shipping_label' => 'custom generation'] , ['increment_id  IN (?)' => $incrementIds]);
vasan
Last edit
vasan
Posted by vasan to vasan's deck (2022-06-28 05:33)