From 8966b76667eb8de528ed4cc935cf4e1d2dec96a8 Mon Sep 17 00:00:00 2001 From: Jonas Staudenmeir Date: Fri, 11 Oct 2024 22:29:22 +0200 Subject: [PATCH] Support HasManyDeep::one() --- src/HasManyDeep.php | 26 ++++++++++++++++++++++++++ tests/HasManyDeepTest.php | 7 +++++++ 2 files changed, 33 insertions(+) diff --git a/src/HasManyDeep.php b/src/HasManyDeep.php index f407cf1..2210c3e 100644 --- a/src/HasManyDeep.php +++ b/src/HasManyDeep.php @@ -238,4 +238,30 @@ public function getLocalKeys() { return $this->localKeys; } + + /** + * Convert the relationship to a "has one deep" relationship. + * + * @phpstan-ignore-next-line + * @return \Staudenmeir\EloquentHasManyDeep\HasOneDeep + */ + public function one() + { + $query = $this->getQuery(); + + $query->getQuery()->joins = []; + + /** @var \Staudenmeir\EloquentHasManyDeep\HasOneDeep $hasOneDeep */ + $hasOneDeep = HasOneDeep::noConstraints( + fn () => new HasOneDeep( + $query, + $this->farParent, + $this->throughParents, + $this->foreignKeys, + $this->localKeys + ) + ); + + return $hasOneDeep; + } } diff --git a/tests/HasManyDeepTest.php b/tests/HasManyDeepTest.php index e10ba66..096bdfa 100644 --- a/tests/HasManyDeepTest.php +++ b/tests/HasManyDeepTest.php @@ -183,4 +183,11 @@ public function testWithTrashedIntermediateAndWithCount(): void $this->assertEquals(3, $country->count); } + + public function testOne(): void + { + $comment = Country::find(1)->comments()->one()->first(); + + $this->assertEquals(31, $comment->id); + } }