laravel icon indicating copy to clipboard operation
laravel copied to clipboard

How to attach relation with pivot value?

Open PitchRE opened this issue 4 years ago • 7 comments

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?

PitchRE avatar Dec 04 '21 16:12 PitchRE

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...

estuardoquan avatar Dec 09 '21 22:12 estuardoquan

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 avatar Dec 10 '21 00:12 PitchRE

@PitchRE https://github.com/laravel-json-api/laravel/issues/114

estuardoquan avatar Dec 13 '21 22:12 estuardoquan

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.

lindyhopchris avatar Jan 02 '22 18:01 lindyhopchris

Any update on this chapter?

ale1981 avatar Jul 26 '22 13:07 ale1981

Is there any update? I'm interested, too.

aon4o avatar Jul 27 '22 12:07 aon4o

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.

lindyhopchris avatar Jul 28 '22 14:07 lindyhopchris