Skip to content

Commit

Permalink
Merge pull request #5572 from Laravel-Backpack/fix-reorder
Browse files Browse the repository at this point in the history
Fix ReorderOperation - replace upsert with 4 update queries
  • Loading branch information
pxpm authored Jul 23, 2024
2 parents cb95ac0 + 994e2b5 commit 908ce84
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions src/app/Library/CrudPanel/Traits/Reorder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Backpack\CRUD\app\Library\CrudPanel\Traits;

use Illuminate\Support\Facades\DB;

/**
* Properties and methods for the Reorder operation.
*/
Expand Down Expand Up @@ -31,22 +33,28 @@ public function updateTreeOrder($request)
$item['depth'] = empty($item['depth']) ? null : (int) $item['depth'];
$item['lft'] = empty($item['left']) ? null : (int) $item['left'];
$item['rgt'] = empty($item['right']) ? null : (int) $item['right'];
// we are not touching those two columns on update, but we need them to be present
// for the upsert query to work. they will just be ignored and not touched.
$item['name'] = '';
$item['slug'] = '';

// unset mapped items properties.
unset($item['item_id'], $item['left'], $item['right']);

return $item;
})->toArray();

$this->model->upsert(
$reorderItems,
$primaryKey,
['parent_id', 'depth', 'lft', 'rgt']
);
DB::transaction(function () use ($reorderItems, $primaryKey, $itemKeys) {
$reorderItemsBindString = implode(',', array_fill(0, count($reorderItems), '?'));
foreach (['parent_id', 'depth', 'lft', 'rgt'] as $column) {
$query = '';
$bindings = [];
$query .= "UPDATE {$this->model->getTable()} SET {$column} = CASE ";
foreach ($reorderItems as $item) {
$query .= "WHEN {$primaryKey} = ? THEN ? ";
$bindings[] = $item[$primaryKey];
$bindings[] = $item[$column];
}
array_push($bindings, ...$itemKeys->toArray());
$query .= "ELSE {$column} END WHERE {$primaryKey} IN ({$reorderItemsBindString})";
DB::statement($query, $bindings);
}
});

return count($reorderItems);
}
Expand Down

0 comments on commit 908ce84

Please sign in to comment.