Skip to content

Commit 2362ed4

Browse files
committed
Add withWhereRelation method to builder
1 parent f03d3a1 commit 2362ed4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,21 @@ public function withWhereHas($relation, ?Closure $callback = null, $operator = '
179179
->with($callback ? [$relation => fn ($query) => $callback($query)] : $relation);
180180
}
181181

182+
/**
183+
* Add a basic where clause to a relationship query and eager-load the relationship.
184+
*
185+
* @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation
186+
* @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
187+
* @param mixed $operator
188+
* @param mixed $value
189+
* @return $this
190+
*/
191+
public function withWhereRelation($relation, $column, $operator = null, $value = null)
192+
{
193+
return $this->whereRelation($relation, $column, $operator, $value)
194+
->with([$relation => fn ($query) => $column instanceof Closure ? $column($query) : $query->where($column, $operator, $value)]);
195+
}
196+
182197
/**
183198
* Add a relationship count / exists condition to the query with where clauses and an "or".
184199
*

tests/Database/DatabaseEloquentMorphOneOfManyTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,23 @@ public function testWithWhereHas()
150150
$this->assertSame($exists->first()->current_state->state, $currentState->state);
151151
}
152152

153+
public function testWithWhereRelation()
154+
{
155+
$product = MorphOneOfManyTestProduct::create();
156+
$currentState = $product->states()->create([
157+
'state' => 'active',
158+
]);
159+
160+
$exists = MorphOneOfManyTestProduct::withWhereRelation('current_state', 'state', 'active')->exists();
161+
$this->assertTrue($exists);
162+
163+
$exists = MorphOneOfManyTestProduct::withWhereRelation('current_state', 'state', 'active')->get();
164+
165+
$this->assertCount(1, $exists);
166+
$this->assertTrue($exists->first()->relationLoaded('current_state'));
167+
$this->assertSame($exists->first()->current_state->state, $currentState->state);
168+
}
169+
153170
public function testWithExists()
154171
{
155172
$product = MorphOneOfManyTestProduct::create();

0 commit comments

Comments
 (0)