laravel-json-api / eloquent

Serialize Eloquent models to JSON API resources
MIT License
12 stars 15 forks source link

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

Open Mina-R-Meshriky opened 3 years ago

Mina-R-Meshriky commented 3 years ago

issue laravel-json-api/laravel#114 if in the request of many-to-many the relationship data contained mata.pivot it will be inserted in the pivot table

'relationships' => [
    'someRelation' => [
        'data' =>  [
          [
            'type' => 'relation-type',
            'id' => 4,
            'meta' => [
                'pivot' => [
                    'someName' => 'value'
                ]
           ]
         ]
        ],
    ],
],

in schema:

BelongsToMany('relationName')
->fields([
     'someName',
     'otherField' => false // default value but will be overridden if submitted in the request
])
 // all fields will default to the convention underscore
->fieldsColumns([
     'someName' => 'database_name'
])

for validation:

[
    'someRelation.*.meta.pivot.someName' => ['required']
]
lindyhopchris commented 3 years ago

Thanks for submitting this. I'm going to have to take a detailed look at it and add tests before I'm happy to merge. I've been really short on open source time recently, but am starting to pick things up again. So hopefully I can get to this sometime in the next month.

CodeNinja1337 commented 3 years ago

Great feature! this is exactly where i was looking for!

CodeNinja1337 commented 2 years ago

@lindyhopchris , any update on this? Because i want to use it but only if its supported by the package. Not as long as its only a open pull request.

lindyhopchris commented 2 years ago

Yeah I've thought about this a bit and my preference would be to do this via existing JSON:API semantics. I believe the spec gives us everything we need to do pivots via intermediary resources. Which also comes with the advantage of the client being able to control things via include paths and sparse fieldsets - which we don't get if we do it via a custom implementation that uses meta.

However, I need to sit down and work my way through a scenario and check that it all works. And if it does then I need to write it up as the definitive way to do it, so that I stop getting constant questions about pivots!! Unfortunately none of the production apps that I have using Laravel JSON:API use pivot values anywhere, which is why I've been slow to write something up.