Skip to content

Commit 3d3c7d6

Browse files
committed
Add MorphTo relation populator
1 parent 7139af7 commit 3d3c7d6

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/Populator.php

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Greabock\Populator\Relation\MorphManyPopulator;
1111
use Greabock\Populator\Relation\MorphOnePopulator;
1212
use Greabock\Populator\Relation\MorphToManyPopulator;
13+
use Greabock\Populator\Relation\MorphToPopulator;
1314
use Greabock\Populator\Relation\RelationPopulator;
1415
use Illuminate\Database\Eloquent\Model;
1516
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -18,6 +19,7 @@
1819
use Illuminate\Database\Eloquent\Relations\HasOne;
1920
use Illuminate\Database\Eloquent\Relations\MorphMany;
2021
use Illuminate\Database\Eloquent\Relations\MorphOne;
22+
use Illuminate\Database\Eloquent\Relations\MorphTo;
2123
use Illuminate\Database\Eloquent\Relations\MorphToMany;
2224
use Illuminate\Database\Eloquent\Relations\Relation;
2325
use Illuminate\Support\Arr;
@@ -143,6 +145,7 @@ protected function populateRelation(Model $model, string $relationName, ?array $
143145
private function initRelationPopulators(): void
144146
{
145147
$this->relationPopulators = [
148+
MorphTo::class => new MorphToPopulator($this->resolver, $this->uow, $this),
146149
HasMany::class => new HasManyPopulator($this->resolver, $this->uow, $this),
147150
BelongsToMany::class => new BelongsToManyPopulator($this->resolver, $this->uow, $this),
148151
BelongsTo::class => new BelongsToPopulator($this->resolver, $this->uow, $this),

src/Relation/MorphToPopulator.php

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
namespace Greabock\Populator\Relation;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Database\Eloquent\Relations\BelongsTo;
7+
use Illuminate\Database\Eloquent\Relations\MorphTo;
8+
use Illuminate\Database\Eloquent\Relations\Relation;
9+
use Illuminate\Support\Str;
10+
11+
class MorphToPopulator extends RelationPopulator
12+
{
13+
/**
14+
* @param Model $model
15+
* @param Relation|MorphTo $relation
16+
* @param array|null $data
17+
* @param string $relationName
18+
* @throws \Exception
19+
*/
20+
function populate(Model $model, Relation $relation, ?array $data, string $relationName): void
21+
{
22+
$related = $this->populator->populate(get_class($relation->getRelated()), $data);
23+
24+
$this->fillRelationField($model, $relation, $related);
25+
26+
$model->setRelation(Str::snake($relation->getRelationName()), $related);
27+
}
28+
29+
protected function fillRelationField(Model $model, BelongsTo $relation, ?Model $related): void
30+
{
31+
$model->{$relation->getForeignKeyName()} = $related ? $related->{$relation->getOwnerKeyName()} : null;
32+
}
33+
}

0 commit comments

Comments
 (0)