Skip to content

Commit

Permalink
Remove extra rows with duplicate keys in SyncsModels trait (librenms#…
Browse files Browse the repository at this point in the history
…13632)

Fixes issues with bad data being left in the DB if it has a duplicate key somehow.
  • Loading branch information
murrant committed Dec 23, 2021
1 parent b27efef commit b38a8e2
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions LibreNMS/DB/SyncsModels.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,31 @@ trait SyncsModels
protected function syncModels($device, $relationship, $models): Collection
{
$models = $models->keyBy->getCompositeKey();
$existing = $device->$relationship->keyBy->getCompositeKey();
$existing = $device->$relationship->groupBy->getCompositeKey();

foreach ($existing as $exist_key => $exist_value) {
foreach ($existing as $exist_key => $existing_rows) {
if ($models->offsetExists($exist_key)) {
// update
$exist_value->fill($models->get($exist_key)->getAttributes())->save();
foreach ($existing_rows as $index => $existing_row) {
if ($index == 0) {
$existing_row->fill($models->get($exist_key)->getAttributes())->save();
} else {
// delete extra rows at this key
$existing_row->delete();
$existing_rows->forget($index);
}
}
} else {
// delete
$exist_value->delete();
$existing_rows->each->delete();
$existing->forget($exist_key);
}
}

$new = $models->diffKeys($existing);
$device->$relationship()->saveMany($new);

return $existing->merge($new);
return $existing->map->first()->merge($new);
}

/**
Expand Down

0 comments on commit b38a8e2

Please sign in to comment.