Skip to content

Instantly share code, notes, and snippets.

@markshust
Created December 7, 2023 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markshust/7911458ed95430c324afaa408a4e4137 to your computer and use it in GitHub Desktop.
Save markshust/7911458ed95430c324afaa408a4e4137 to your computer and use it in GitHub Desktop.
Modify a Magento SQL database where condition with an alternate condition
<?php
...
/**
* Modify a WHERE condition in a collection's select statement.
*
* @param \Magento\Framework\Data\Collection\AbstractDb $collection The collection to modify.
* @param string $searchCondition The condition part to search for in the WHERE clause.
* @param string $replaceCondition The condition part to replace with in the WHERE clause.
* @return void
*/
function modifyWhereCondition($collection, $searchCondition, $replaceCondition) {
// Get the WHERE part of the query
$where = $collection->getSelect()->getPart(\Magento\Framework\DB\Select::WHERE);
// Clear the WHERE part of the query
$collection->getSelect()->reset(\Magento\Framework\DB\Select::WHERE);
// Iterate over each WHERE condition and make replacements as necessary
foreach ($where as $key => $value) {
if (str_contains($value, $searchCondition)) {
$where[$key] = str_replace($searchCondition, $replaceCondition, $value);
}
}
// Set the modified WHERE part back into the collection's select statement
$collection->getSelect()->setPart(\Magento\Framework\DB\Select::WHERE, $where);
}
// Usage example:
// Assuming $collection is your collection instance, modify the WHERE condition as needed.
modifyWhereCondition(
$collection,
'stock_status_index.stock_status = 1',
'(stock_status_index.stock_status = 1 OR e.status = 1)'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment