Skip to content

Commit

Permalink
Save a COUNT query if all records should be kept
Browse files Browse the repository at this point in the history
This query turned out to be the bottleneck on a project of mine. If you intend to keep all versions there is no need to count them.
  • Loading branch information
fedeisas authored Jan 13, 2020
1 parent b7c1bbe commit ef5832a
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/Mpociot/Versionable/VersionableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,20 @@ protected function versionablePostSave()
private function purgeOldVersions()
{
$keep = isset($this->keepOldVersions) ? $this->keepOldVersions : 0;
$count = $this->versions()->count();

if ((int)$keep > 0 && $count > $keep) {
$oldVersions = $this->versions()
->latest()
->take($count)
->skip($keep)
->get()
->each(function ($version) {
$version->delete();
});

if ((int)$keep > 0) {
$count = $this->versions()->count();

if ($count > $keep) {
$oldVersions = $this->versions()
->latest()
->take($count)
->skip($keep)
->get()
->each(function ($version) {
$version->delete();
});
}
}
}

Expand Down

0 comments on commit ef5832a

Please sign in to comment.