Skip to content

Commit d961975

Browse files
authored
Add support for eager loading specific columns to withWhereHas (#45168)
* Add eager loading specific columns support to withWhereHas * Add tests
1 parent 1dc5970 commit d961975

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ public function whereHas($relation, Closure $callback = null, $operator = '>=',
165165
*/
166166
public function withWhereHas($relation, Closure $callback = null, $operator = '>=', $count = 1)
167167
{
168-
return $this->whereHas($relation, $callback, $operator, $count)
168+
return $this->whereHas(Str::before($relation, ':'), $callback, $operator, $count)
169169
->with($callback ? [$relation => fn ($query) => $callback($query)] : $relation);
170170
}
171171

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,17 @@ public function testEagerLoadingWithColumns()
494494
$closure($builder);
495495
}
496496

497+
public function testWithWhereHasWithSpecificColumns()
498+
{
499+
$model = new EloquentModelWithWhereHasStub;
500+
$instance = $model->newInstance()->newQuery()->withWhereHas('foo:diaa,fares');
501+
$builder = m::mock(Builder::class);
502+
$builder->shouldReceive('select')->once()->with(['diaa', 'fares']);
503+
$this->assertNotNull($instance->getEagerLoads()['foo']);
504+
$closure = $instance->getEagerLoads()['foo'];
505+
$closure($builder);
506+
}
507+
497508
public function testWithMethodCallsQueryBuilderCorrectlyWithArray()
498509
{
499510
$result = EloquentModelWithStub::with(['foo', 'bar']);
@@ -2858,6 +2869,14 @@ public function newQuery()
28582869
}
28592870
}
28602871

2872+
class EloquentModelWithWhereHasStub extends Model
2873+
{
2874+
public function foo()
2875+
{
2876+
return $this->hasMany(EloquentModelStub::class);
2877+
}
2878+
}
2879+
28612880
class EloquentModelWithoutRelationStub extends Model
28622881
{
28632882
public $with = ['foo'];

0 commit comments

Comments
 (0)