Skip to content

Commit 335b30e

Browse files
committed
Fix aggregation alias
1 parent 1d4699e commit 335b30e

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/Eloquent/Builder.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ public function withAggregate($relations, $column, $function = null)
342342

343343
$alias = match (true) {
344344
count($segments) === 1 => Str::snake($segments[0]) . '_' . $function,
345-
count($segments) === 3 && Str::lower($segments[1]) => $segments[2],
345+
count($segments) === 3 && Str::lower($segments[1]) === 'as' => $segments[2],
346346
default => throw new InvalidArgumentException(sprintf('Invalid relation name format. Expected "relation as alias" or "relation", got "%s"', $name)),
347347
};
348348
$name = $segments[0];

tests/Eloquent/EloquentWithAggregateTest.php

+40
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use MongoDB\Laravel\Tests\Eloquent\Models\EloquentWithAggregateModel3;
1212
use MongoDB\Laravel\Tests\Eloquent\Models\EloquentWithAggregateModel4;
1313
use MongoDB\Laravel\Tests\TestCase;
14+
use PHPUnit\Framework\Attributes\TestWith;
1415

1516
use function count;
1617
use function ksort;
@@ -55,6 +56,45 @@ public function testWithAggregate()
5556
], $results->get());
5657
}
5758

59+
public function testWithAggregateAlias()
60+
{
61+
EloquentWithAggregateModel1::create(['id' => 1]);
62+
$one = EloquentWithAggregateModel1::create(['id' => 2]);
63+
$one->twos()->create(['value' => 4]);
64+
$one->twos()->create(['value' => 6]);
65+
66+
$results = EloquentWithAggregateModel1::withCount('twos as result')->where('id', 2);
67+
self::assertSameResults([
68+
['id' => 2, 'result' => 2],
69+
], $results->get());
70+
71+
$results = EloquentWithAggregateModel1::withMax('twos as result', 'value')->where('id', 2);
72+
self::assertSameResults([
73+
['id' => 2, 'result' => 6],
74+
], $results->get());
75+
76+
$results = EloquentWithAggregateModel1::withMin('twos as result', 'value')->where('id', 2);
77+
self::assertSameResults([
78+
['id' => 2, 'result' => 4],
79+
], $results->get());
80+
81+
$results = EloquentWithAggregateModel1::withAvg('twos as result', 'value')->where('id', 2);
82+
self::assertSameResults([
83+
['id' => 2, 'result' => 5.0],
84+
], $results->get());
85+
}
86+
87+
#[TestWith(['withCount'])]
88+
#[TestWith(['withMax'])]
89+
#[TestWith(['withMin'])]
90+
#[TestWith(['withAvg'])]
91+
public function testWithAggregateInvalidAlias(string $method)
92+
{
93+
self::expectException(InvalidArgumentException::class);
94+
self::expectExceptionMessage('Expected "relation as alias" or "relation", got "twos foo result"');
95+
EloquentWithAggregateModel1::{$method}('twos foo result', 'value')->get();
96+
}
97+
5898
public function testWithAggregateEmbed()
5999
{
60100
EloquentWithAggregateModel1::create(['id' => 1]);

0 commit comments

Comments
 (0)