diff --git a/src/Eloquent/EmbedsRelations.php b/src/Eloquent/EmbedsRelations.php index d5984b08e..da02cf7ae 100644 --- a/src/Eloquent/EmbedsRelations.php +++ b/src/Eloquent/EmbedsRelations.php @@ -28,7 +28,7 @@ trait EmbedsRelations * * @return EmbedsMany */ - protected function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null) + public function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null) { // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most @@ -53,7 +53,7 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r } /** - * Define an embedded one-to-many relationship. + * Define an embedded one-to-one relationship. * * @param class-string $related * @param string|null $localKey @@ -62,7 +62,7 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r * * @return EmbedsOne */ - protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) + public function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) { // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most diff --git a/tests/EmbeddedRelationsTest.php b/tests/EmbeddedRelationsTest.php index 1c68e2d34..ac84851d9 100644 --- a/tests/EmbeddedRelationsTest.php +++ b/tests/EmbeddedRelationsTest.php @@ -972,4 +972,28 @@ public function testUnsetPropertyOnEmbed() $this->assertNull($user->addresses->get(0)->city); $this->assertSame('Kyoto', $user->addresses->get(1)->city); } + + public function testResolveRelationUsingEmbedsMany() + { + User::resolveRelationUsing('dynamicAddresses', fn (User $model) => $model->embedsMany(Address::class, 'addresses', 'user_id', 'dynamicAddresses')); + + $user = User::create(['name' => 'John Doe']); + $user->dynamicAddresses()->save(new Address(['city' => 'London'])); + + $user = User::find($user->id); + $this->assertCount(1, $user->dynamicAddresses); + $this->assertEquals('London', $user->dynamicAddresses->first()->city); + } + + public function testResolveRelationUsingEmbedsOne() + { + User::resolveRelationUsing('dynamicFather', fn (User $model) => $model->embedsOne(User::class, 'father', 'user_id', 'dynamicFather')); + + $user = User::create(['name' => 'John Doe']); + $user->dynamicFather()->save(new User(['name' => 'Mark Doe'])); + + $user = User::find($user->id); + $this->assertNotNull($user->dynamicFather); + $this->assertEquals('Mark Doe', $user->dynamicFather->name); + } }