Skip to content

Commit

Permalink
Fix HasManyThrough::one() (#53119)
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir authored Oct 12, 2024
1 parent 4b52e6d commit 57d6188
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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(),
Expand Down
18 changes: 18 additions & 0 deletions tests/Integration/Database/EloquentHasManyThroughTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 57d6188

Please sign in to comment.