Skip to content

Commit

Permalink
Use left join to optimize prune query
Browse files Browse the repository at this point in the history
  • Loading branch information
erikn69 committed Jun 26, 2024
1 parent db5ed9c commit c0ff649
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions src/Drivers/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,22 @@ public function audit(Auditable $model): ?Audit
public function prune(Auditable $model): bool
{
if (($threshold = $model->getAuditThreshold()) > 0) {
$class = get_class($model->audits()->getModel());
$keyName = (new $class)->getKeyName();

$idsToKeep = $model->audits()
->select($keyName)
->limit($threshold)
->latest()
->pluck($keyName);

$auditClass = get_class($model->audits()->getModel());
$auditModel = new $auditClass;

return $model->audits()
->whereNotIn($keyName, $idsToKeep)
->leftJoinSub(
$model->audits()->select($auditModel->getKeyName())->limit($threshold)->latest(),
'audit_threshold',
function ($join) use ($auditModel) {
$join->on(
$auditModel->gettable().'.'.$auditModel->getKeyName(),
'=',
'audit_threshold.'.$auditModel->getKeyName()
);
}
)
->whereNull('audit_threshold.'.$auditModel->getKeyName())
->delete() > 0;
}

Expand Down

0 comments on commit c0ff649

Please sign in to comment.