laravel
laravel copied to clipboard
How to attach relation with pivot value?
How I can add pivot values to attach action?
public function attachCollectionItems(
UserSchema $schema,
UserRequest $request,
User $user
) {
$collectionItems = $schema
->repository()
->modifyToMany($user, 'collection-items')
->attach($request->validatedForRelation(), ['status' => 1]);
}
The problem is that attach() is not native laravel method. I cannot add pivot values there. Is there a way to to do that using that package or i'll have to write this method myself completely?
if I'm not wrong, you should declare this on your schema... leave the controller action alone and add in the schema... BelongsToMany::make('relation')->fields(['pivot_field' => 'value']) ref: https://laraveljsonapi.io/docs/1.0/schemas/relationships.html#belongs-to-many
I suppose, but this is still pure conjecture... that its the equivalent to writing inside of the schema's model a function like such:
public function relation(){
return $this->belongsToMany(Relation::class)->withPivotValue('column','value');
}
which also works; writes on create declared pivot value and "filters" relationships from same table through same pivot value...
This assumes that pivot value will be static or calculated on server somehow.
I want to attach relationship to model with extra pivot value that will be included in payload.
@PitchRE https://github.com/laravel-json-api/laravel/issues/114
This question is coming up so much that I plan to write a chapter in the docs specifically for dealing with pivot values.
In short, the summary is that the JSON:API spec does not have such a thing as "pivot values". However, it is easy to implement this using a pivot model and representing that in the API as a specific resource. That for me is the way to support this - as it complies with the spec (which is what this package is all about).
I'll post here again once I've written the chapter.
Any update on this chapter?
Is there any update? I'm interested, too.
No I still need to deal with this. I'm not on Open Source at the moment but should be returning to it soon, so will prioritise this then. I need to make actual code changes which is what is blocking me on this at the moment.