Insert or update in magento

Insert or update in magento

August 8, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Insert or update in magento

Inserting or Updating Data Based on Unique Constraint in Magento

Magento provides robust database connectivity through its resource model. If you’re working with tables that have unique constraints, you might face challenges when trying to insert or update data based on existing values.

Understanding the Issue

In your case, you’re inserting rows into a table using the insertMultiple method from the core write connection. This method throws an error if there are any duplicate primary key values in the array of inserted rows. However, you want to check for duplicates in a specific column (order_id) before performing the insert or update operation.

Achieving Insert or Update Based on Unique Constraint

To achieve this in Magento, you can follow these steps:

  1. Fetch Existing Data: Before inserting new data, fetch all existing records from the table based on the unique constraint column (order_id).
$table = Mage::getSingleton('core/resource')->getTableName('your_table_name');
$read = Mage::getSingleton('core/resource')->getConnection('core_read');

$query = "SELECT * FROM $table WHERE order_id IN ('".implode("', '", array_unique(array_column($rows, 'order_id')))."')";
$existingRows = $read->fetchAll($query);
  1. Prepare Update and Insert Data: Loop through your data array and compare each row with the existing rows fetched in step 1.
$insertData = [];
$updateData = [];

foreach ($rows as $row) {
    $exists = false;

    foreach ($existingRows as $existingRow) {
        if ($existingRow['order_id'] == $row['order_id']) {
            $exists = true;
            break;
        }
    }

    if ($exists) {
        $updateData[] = array_merge($existingRow, $row); // Merge existing and new data for an update operation
    } else {
        $insertData[] = $row; // Add new row to insert array
    }
}
  1. Perform Update Operation: If you have any rows in the $updateData array, perform an update operation using the updateMultiple method.
if (!empty($updateData)) {
    $write->updateMultiple($table, $updateData);
}
  1. Perform Insert Operation: If there are still new rows to insert after the update operation, use the insertMultiple method as before.
$newRows = array_diff_key($rows, $existingRows);

if (!empty($newRows)) {
    $write->insertMultiple($table, $newRows);
}

Best Practices

  • Always validate your data before performing database operations to prevent any potential errors.
  • Use Magento’s built-in exception handling for database operations to ensure proper error reporting and recovery.

Remember that direct database manipulation in Magento should be used sparingly. The platform provides many other ways to interact with the database through its models, repositories, and collections.

Conclusion

Inserting or updating data based on unique constraints in Magento requires a strategic approach. By fetching existing data and comparing it with your new data, you can effectively perform insert or update operations while respecting the integrity of your database schema.

If you’re looking for more advanced techniques and best practices in Magento development, be sure to check out our Magento Development Guide at Laravel Company.

Database Orders Errors

Our network