Skip to content

Commit 57d6188

Browse files
authored
Fix HasManyThrough::one() (#53119)
1 parent 4b52e6d commit 57d6188

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Database\Eloquent\Relations;
44

5+
use Illuminate\Database\Eloquent\Builder;
56
use Illuminate\Database\Eloquent\Collection;
67
use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
78

@@ -24,7 +25,7 @@ class HasManyThrough extends HasOneOrManyThrough
2425
public function one()
2526
{
2627
return HasOneThrough::noConstraints(fn () => new HasOneThrough(
27-
$this->getQuery(),
28+
tap($this->getQuery(), fn (Builder $query) => $query->getQuery()->joins = []),
2829
$this->farParent,
2930
$this->throughParent,
3031
$this->getFirstKeyName(),

tests/Integration/Database/EloquentHasManyThroughTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Illuminate\Tests\Integration\Database\EloquentHasManyThroughTest;
44

55
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
67
use Illuminate\Database\Eloquent\SoftDeletes;
78
use Illuminate\Database\Schema\Blueprint;
89
use Illuminate\Support\Facades\DB;
@@ -381,6 +382,18 @@ public function testCanReplicateModelLoadedThroughHasManyThrough()
381382
$newArticle->title .= ' v2';
382383
$newArticle->save();
383384
}
385+
386+
public function testOne(): void
387+
{
388+
$team = Team::create();
389+
390+
$user = User::create(['team_id' => $team->id, 'name' => Str::random()]);
391+
392+
Article::create(['user_id' => $user->id, 'title' => Str::random(), 'created_at' => now()->subDay()]);
393+
$latestArticle = Article::create(['user_id' => $user->id, 'title' => Str::random(), 'created_at' => now()]);
394+
395+
$this->assertEquals($latestArticle->id, $team->latestArticle->id);
396+
}
384397
}
385398

386399
class User extends Model
@@ -474,6 +487,11 @@ public function articles()
474487
{
475488
return $this->hasManyThrough(Article::class, User::class);
476489
}
490+
491+
public function latestArticle(): HasOneThrough
492+
{
493+
return $this->articles()->one()->latest();
494+
}
477495
}
478496

479497
class Category extends Model

0 commit comments

Comments
 (0)