Skip to content

Commit d1b8c89

Browse files
[11.x] Add withWhereRelation method to builder (#54668)
* Add `withWhereRelation` method to builder * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 59a40eb commit d1b8c89

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,25 @@ public function whereRelation($relation, $column, $operator = null, $value = nul
437437
});
438438
}
439439

440+
/**
441+
* Add a basic where clause to a relationship query and eager-load the relationship with the same conditions.
442+
*
443+
* @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation
444+
* @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
445+
* @param mixed $operator
446+
* @param mixed $value
447+
* @return $this
448+
*/
449+
public function withWhereRelation($relation, $column, $operator = null, $value = null)
450+
{
451+
return $this->whereRelation($relation, $column, $operator, $value)
452+
->with([
453+
$relation => fn ($query) => $column instanceof Closure
454+
? $column($query)
455+
: $query->where($column, $operator, $value)
456+
]);
457+
}
458+
440459
/**
441460
* Add an "or where" clause to a relationship query.
442461
*

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)