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); + } }