diff --git a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php index 5249ac33147e..1399df347ed9 100644 --- a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php @@ -2,6 +2,7 @@ namespace Illuminate\Database\Eloquent\Relations; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary; @@ -24,7 +25,7 @@ class HasManyThrough extends HasOneOrManyThrough public function one() { return HasOneThrough::noConstraints(fn () => new HasOneThrough( - $this->getQuery(), + tap($this->getQuery(), fn (Builder $query) => $query->getQuery()->joins = []), $this->farParent, $this->throughParent, $this->getFirstKeyName(), diff --git a/tests/Integration/Database/EloquentHasManyThroughTest.php b/tests/Integration/Database/EloquentHasManyThroughTest.php index 68e8363182b4..325a450ad7ef 100644 --- a/tests/Integration/Database/EloquentHasManyThroughTest.php +++ b/tests/Integration/Database/EloquentHasManyThroughTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Integration\Database\EloquentHasManyThroughTest; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\HasOneThrough; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; @@ -381,6 +382,18 @@ public function testCanReplicateModelLoadedThroughHasManyThrough() $newArticle->title .= ' v2'; $newArticle->save(); } + + public function testOne(): void + { + $team = Team::create(); + + $user = User::create(['team_id' => $team->id, 'name' => Str::random()]); + + Article::create(['user_id' => $user->id, 'title' => Str::random(), 'created_at' => now()->subDay()]); + $latestArticle = Article::create(['user_id' => $user->id, 'title' => Str::random(), 'created_at' => now()]); + + $this->assertEquals($latestArticle->id, $team->latestArticle->id); + } } class User extends Model @@ -474,6 +487,11 @@ public function articles() { return $this->hasManyThrough(Article::class, User::class); } + + public function latestArticle(): HasOneThrough + { + return $this->articles()->one()->latest(); + } } class Category extends Model