Skip to content

Commit

Permalink
fix: add newest relation to model, relations are cached and the mutat…
Browse files Browse the repository at this point in the history
…or in HasRevisions using it will only generate 1 query
  • Loading branch information
a-drew committed Dec 15, 2021
1 parent 2387fd5 commit ff034b8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Concerns/HasRevisions.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ public function getNewestIdAttribute($value)
if ($value !== null || array_key_exists('newest_id', $this->attributes)) {
return $value;
}
// dependency on latest boolean column, alternative to using max id
return $this->revisions()->where('latest', true)->first()->revisionable_id ?? null;
// when value isn't set by extra subselect scope, fetch from relations
return $this->revision->newest->revisionable_id ?? null;
}


Expand Down
13 changes: 13 additions & 0 deletions src/Models/Revision.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* @property-read int|null $all_revisions_count
* @property-read \Illuminate\Database\Eloquent\Collection|Revision[] $otherRevisions
* @property-read int|null $other_revisions_count
* @property-read Revision|null $newest
* @property-read Revision|null $next
* @property-read Revision|null $previous
* @property-read Checkpoint|null $checkpoint
Expand Down Expand Up @@ -216,6 +217,18 @@ public function next(): HasOne
return $this->hasOne(static::class, 'previous_revision_id', $this->getKeyName());
}

/**
* Return latest revision
*
* @return HasOne
*/
public function newest(): HasOne
{
return $this->hasOne(static::class, 'revisionable_type', 'revisionable_type')
->where('original_revisionable_id', $this->original_revisionable_id)
->where('latest', true)->latest();
}

/**
* Returns true if this is the most current revision for an item
*
Expand Down

0 comments on commit ff034b8

Please sign in to comment.