Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Fix HasManyThrough::one() #53119

Merged
merged 1 commit into from
Oct 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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