Skip to content

Commit

Permalink
Support HasManyDeep::one()
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir committed Oct 11, 2024
1 parent 1531dac commit 8966b76
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/HasManyDeep.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<TRelatedModel, TDeclaringModel>
*/
public function one()
{
$query = $this->getQuery();

$query->getQuery()->joins = [];

/** @var \Staudenmeir\EloquentHasManyDeep\HasOneDeep<TRelatedModel, TDeclaringModel> $hasOneDeep */
$hasOneDeep = HasOneDeep::noConstraints(
fn () => new HasOneDeep(
$query,
$this->farParent,
$this->throughParents,
$this->foreignKeys,
$this->localKeys
)
);

return $hasOneDeep;
}
}
7 changes: 7 additions & 0 deletions tests/HasManyDeepTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 8966b76

Please sign in to comment.