From ef5832a0d7e6bb0b38a08175e9e3dd9cb202bed7 Mon Sep 17 00:00:00 2001 From: Fede Isas Date: Mon, 13 Jan 2020 20:24:07 -0300 Subject: [PATCH] Save a COUNT query if all records should be kept 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. --- src/Mpociot/Versionable/VersionableTrait.php | 25 +++++++++++--------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/Mpociot/Versionable/VersionableTrait.php b/src/Mpociot/Versionable/VersionableTrait.php index cb377ed..2ae2f8a 100644 --- a/src/Mpociot/Versionable/VersionableTrait.php +++ b/src/Mpociot/Versionable/VersionableTrait.php @@ -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(); + }); + } } }