diff --git a/src/VersioningScope.php b/src/VersioningScope.php index 72a23ad..adc6698 100644 --- a/src/VersioningScope.php +++ b/src/VersioningScope.php @@ -33,6 +33,25 @@ public function apply(Builder $builder, Model $model) $this->extend($builder); } + /** + * Remove the scope from the given Eloquent query builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + public function remove(Builder $builder, Model $model) + { + $table = $model->getVersionTable(); + + $query = $builder->getQuery(); + + $query->joins = collect($query->joins)->reject(function($join) use ($table) + { + return $this->isVersionJoinConstraint($join, $table); + })->values()->all(); + } + /** * Extend the query builder with the needed functions. * @@ -58,7 +77,9 @@ protected function addVersion(Builder $builder) $builder->macro('version', function(Builder $builder, $version) { $model = $builder->getModel(); - $builder->withoutGlobalScope($this)->join($model->getVersionTable(), function($join) use ($model, $version) { + $this->remove($builder, $builder->getModel()); + + $builder->join($model->getVersionTable(), function($join) use ($model, $version) { $join->on($model->getQualifiedKeyName(), '=', $model->getQualifiedVersionKeyName()); $join->where($model->getQualifiedVersionColumn(), '=', $version); }); @@ -78,7 +99,9 @@ protected function addAllVersions(Builder $builder) $builder->macro('allVersions', function(Builder $builder) { $model = $builder->getModel(); - $builder->withoutGlobalScope($this)->join($model->getVersionTable(), function($join) use ($model) { + $this->remove($builder, $builder->getModel()); + + $builder->join($model->getVersionTable(), function($join) use ($model) { $join->on($model->getQualifiedKeyName(), '=', $model->getQualifiedVersionKeyName()); }); @@ -86,4 +109,16 @@ protected function addAllVersions(Builder $builder) }); } + /** + * Determine if the given join clause is a version constraint. + * + * @param \Illuminate\Database\Query\JoinClause $join + * @param string $column + * @return bool + */ + protected function isVersionJoinConstraint(JoinClause $join, $table) + { + return $join->type == 'inner' && $join->table == $table; + } + }