Skip to content

Commit

Permalink
Make withTrashed() work with whereHas()
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir committed Mar 10, 2022
1 parent e5ab941 commit 8316d27
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/Relations/BelongsToThrough.php
Expand Up @@ -98,7 +98,11 @@ protected function performJoins(Builder $query = null)
$query->join($model->getTable(), $first, '=', $second);

if ($this->hasSoftDeletes($model)) {
$this->query->whereNull($model->getQualifiedDeletedAtColumn());
$column= $model->getQualifiedDeletedAtColumn();

$query->withGlobalScope(__CLASS__ . ":$column", function (Builder $query) use ($column) {
$query->whereNull($column);
});
}
}
}
Expand Down Expand Up @@ -287,10 +291,9 @@ public function withTrashed(...$columns)
$columns = $columns[0];
}

$this->query->getQuery()->wheres = collect($this->query->getQuery()->wheres)
->reject(function ($where) use ($columns) {
return $where['type'] === 'Null' && in_array($where['column'], $columns);
})->values()->all();
foreach ($columns as $column) {
$this->query->withoutGlobalScope(__CLASS__ . ":$column");
}

return $this;
}
Expand Down
7 changes: 7 additions & 0 deletions tests/BelongsToThroughTest.php
Expand Up @@ -119,6 +119,13 @@ public function testWithTrashedIntermediate()
$this->assertEquals(3, $country->id);
}

public function testWithTrashedIntermediateAndWhereHas()
{
$comments = Comment::has('countryWithTrashedUser')->get();

$this->assertEquals([31, 32, 33], $comments->pluck('id')->all());
}

public function testGetThroughParents()
{
$throughParents = Comment::first()->country()->getThroughParents();
Expand Down
5 changes: 5 additions & 0 deletions tests/Models/Comment.php
Expand Up @@ -24,6 +24,11 @@ public function countryWithCustomForeignKeys()
);
}

public function countryWithTrashedUser()
{
return $this->country()->withTrashed(['users.deleted_at']);
}

public function countryWithPrefix()
{
return $this->belongsToThrough(Country::class, [User::class, Post::class], null, 'custom_');
Expand Down

0 comments on commit 8316d27

Please sign in to comment.