Skip to content

Commit b911037

Browse files
author
Peter Klooster
committed
Added moment scope (select the version at a specific point in time)
1 parent fb486f6 commit b911037

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/VersioningScope.php

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Database\Eloquent\Model;
77
use Illuminate\Database\Eloquent\Scope;
88
use Illuminate\Database\Query\JoinClause;
9+
use Carbon\Carbon;
910

1011
class VersioningScope implements Scope
1112
{
@@ -14,7 +15,7 @@ class VersioningScope implements Scope
1415
*
1516
* @var array
1617
*/
17-
protected $extensions = ['Version', 'AllVersions'];
18+
protected $extensions = ['Version', 'AllVersions', 'Moment'];
1819

1920
/**
2021
* Apply the scope to a given Eloquent query builder.
@@ -111,6 +112,28 @@ protected function addAllVersions(Builder $builder)
111112
});
112113
}
113114

115+
/**
116+
* Add the moment extension to the builder.
117+
*
118+
* @param \Illuminate\Database\Eloquent\Builder $builder
119+
* @return void
120+
*/
121+
protected function addMoment(Builder $builder)
122+
{
123+
$builder->macro('moment', function(Builder $builder, Carbon $moment) {
124+
$model = $builder->getModel();
125+
126+
$this->remove($builder, $builder->getModel());
127+
128+
$builder->join($model->getVersionTable(), function($join) use ($model, $moment) {
129+
$join->on($model->getQualifiedKeyName(), '=', $model->getQualifiedVersionKeyName());
130+
$join->where('updated_at', '<=', $moment)->orderBy('updated_at', 'desc')->limit(1);
131+
})->orderBy('updated_at', 'desc')->limit(1);
132+
133+
return $builder;
134+
});
135+
}
136+
114137
/**
115138
* Determine if the given join clause is a version constraint.
116139
*

0 commit comments

Comments
 (0)