From 3d3c7d63903e52c53c1c704afc4effc24a6f2295 Mon Sep 17 00:00:00 2001 From: Greabock Date: Mon, 14 Oct 2019 10:20:23 +0300 Subject: [PATCH] Add MorphTo relation populator --- src/Populator.php | 3 +++ src/Relation/MorphToPopulator.php | 33 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/Relation/MorphToPopulator.php diff --git a/src/Populator.php b/src/Populator.php index 82ad2e3..a9593f3 100644 --- a/src/Populator.php +++ b/src/Populator.php @@ -10,6 +10,7 @@ use Greabock\Populator\Relation\MorphManyPopulator; use Greabock\Populator\Relation\MorphOnePopulator; use Greabock\Populator\Relation\MorphToManyPopulator; +use Greabock\Populator\Relation\MorphToPopulator; use Greabock\Populator\Relation\RelationPopulator; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -18,6 +19,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphOne; +use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Arr; @@ -143,6 +145,7 @@ protected function populateRelation(Model $model, string $relationName, ?array $ private function initRelationPopulators(): void { $this->relationPopulators = [ + MorphTo::class => new MorphToPopulator($this->resolver, $this->uow, $this), HasMany::class => new HasManyPopulator($this->resolver, $this->uow, $this), BelongsToMany::class => new BelongsToManyPopulator($this->resolver, $this->uow, $this), BelongsTo::class => new BelongsToPopulator($this->resolver, $this->uow, $this), diff --git a/src/Relation/MorphToPopulator.php b/src/Relation/MorphToPopulator.php new file mode 100644 index 0000000..ab147de --- /dev/null +++ b/src/Relation/MorphToPopulator.php @@ -0,0 +1,33 @@ +populator->populate(get_class($relation->getRelated()), $data); + + $this->fillRelationField($model, $relation, $related); + + $model->setRelation(Str::snake($relation->getRelationName()), $related); + } + + protected function fillRelationField(Model $model, BelongsTo $relation, ?Model $related): void + { + $model->{$relation->getForeignKeyName()} = $related ? $related->{$relation->getOwnerKeyName()} : null; + } +}