Skip to content

Adding support to fill pivot data in many-to-many relations #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 68 additions & 4 deletions src/Fields/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMany;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use LaravelJsonApi\Core\Schema\IdParser;
use LaravelJsonApi\Core\Support\Str;
use LaravelJsonApi\Eloquent\Contracts\FillableToMany;
use LaravelJsonApi\Eloquent\Fields\Concerns\ReadOnly;
use LogicException;
Expand Down Expand Up @@ -51,6 +54,11 @@ public static function make(string $fieldName, string $relation = null): Belongs
*/
private $pivot;

/**
* @var array
*/
private $fieldsColumns;

/**
* Set the values or callback to use for pivot attributes.
*
Expand All @@ -68,6 +76,23 @@ public function fields($pivot): self
return $this;
}

/**
* Set a different database column name
*
* @param $fieldsColumns
* @return $this
*/
public function fieldsColumns($fieldsColumns): self
{
if (!is_array($fieldsColumns)) {
throw new InvalidArgumentException('Expecting an array value.');
}

$this->fieldsColumns = $fieldsColumns;

return $this;
}

/**
* @return iterable
*/
Expand Down Expand Up @@ -103,7 +128,8 @@ public function sync(Model $model, array $identifiers): iterable
$relation->sync($this->formatAttachRecords(
$model,
$relation,
$related
$related,
$identifiers
));

$model->setRelation($this->relationName(), $related);
Expand Down Expand Up @@ -131,7 +157,8 @@ public function attach(Model $model, array $identifiers): iterable
$relation->attach($this->formatAttachRecords(
$model,
$relation,
$related->diff($existing)
$related->diff($existing),
$identifiers
));

$model->unsetRelation($this->relationName());
Expand Down Expand Up @@ -175,17 +202,19 @@ private function getRelation(Model $model): EloquentBelongsToMany
* @param Model $parent
* @param EloquentBelongsToMany $relation
* @param EloquentCollection $models
* @param array $identifiers
* @return array
*/
private function formatAttachRecords(
Model $parent,
EloquentBelongsToMany $relation,
EloquentCollection $models
EloquentCollection $models,
array $identifiers
): array
{
return $models
->keyBy(static fn($related) => $related->{$relation->getRelatedKeyName()})
->map(fn($related) => $this->getPivotAttributes($parent, $related))
->map(fn($related) => $this->setPivotAttributes($parent, $related, $identifiers))
->all();
}

Expand All @@ -207,4 +236,39 @@ private function getPivotAttributes(Model $parent, Model $related): array
return [];
}

/**
* @param Model $parent
* @param Model $related
* @param array $identifiers
* @return array
*/
private function setPivotAttributes(Model $parent, Model $related, array $identifiers): array
{
$attributes = [];
$pivotAttributes = $this->getPivotAttributes($parent, $related);
$parser = IdParser::make($this->schemas()->schemaForModel($related)->id());

$metaPivot = collect($identifiers)
->where('id', '=', $parser->encodeId($related->getKey()))
->pluck('meta.pivot')
->first();

foreach ($pivotAttributes as $key => $keyOrDefaultValue) {
if (is_int($key)) {
// then value of that key should be inserted by user, it has no default value
if ($newValue = Arr::get($metaPivot, $keyOrDefaultValue)) {
$attributes[$this->fieldsColumns[$keyOrDefaultValue] ?? Str::underscore($keyOrDefaultValue)] = $newValue;
}
} else {
if ($overrideValue = Arr::get($metaPivot, $key)) {
$attributes[$this->fieldsColumns[$key] ?? Str::underscore($key)] = $overrideValue;
} else {
$attributes[$this->fieldsColumns[$key] ?? Str::underscore($key)] = $keyOrDefaultValue;
}
}
}

return $attributes;
}

}