swisnl / json-api-client

A PHP package for mapping remote {json:api} resources to Eloquent like models and collections.
MIT License
205 stars 24 forks source link

How to set a relation to "null"? #66

Closed V-Orbit closed 5 years ago

V-Orbit commented 5 years ago

Hi @JaZo ! Just don't figure how to set a relation to null when saving a content which had a previous relation set. Relation "publisher" is a hasOne relation

This is the attributes/relations array prior to hydration. this array works as expected.

$ordineAttributes = [
                    note => $datiForm['note'],
                    'totale_ordine' => $datiForm['totale_ordine'],
                    'stato' => [
                        'id' => base64_decode($datiForm['stato'])
                    ],

/* THIS IS THE RELATION I WANT TO EVENTUALLY SET TO NULL (OR SOMEWHAT SIMILAR) */
                    'publisher' => [
                         'id' => $datiForm['publisher']
                    ],

                    'cliente' => [
                        'id' => $datiForm['cliente_id']
                    ],
                    'righe_ordine' => $ids,
                ];

$itemOrdineDocument = $itemHydrator->hydrate(
                        $typeMapper->getMapping('node--ordini'), 
                        $ordineAttributes,
                        $orderID
                ); 

I already tried to:

Of course, if I completely remove the publisher entry from the ordineAttributes array, the hydrator steps over and leaves the previous value unchanged.

What I'm doing wrong?

I also get errors when I do

$itemOrdineDocument->unsetRelation('publisher');
$ordineRepo->save($itemOrdineDocument);
JaZo commented 5 years ago

Good point! Currently you can't set a relation to null using the ItemHydrator, but you can do it manually:

$item = $typeMapper->getMapping('node--ordini');
$item->publisher()->dissociate();

I'll leave this issue open to implement this in the ItemHydrator!

V-Orbit commented 5 years ago

Good point! Currently you can't set a relation to null using the ItemHydrator, but you can do it manually:

$item = $typeMapper->getMapping('node--ordini');
$item->publisher()->dissociate();

I'll leave this issue open to implement this in the ItemHydrator!

@JaZo fantastic! So I hit the point. Figuring out the way to workaround that, I implemented the setter exactly as you stated, really little before you wrote the comment :-D

JaZo commented 5 years ago

@V-Orbit, 1.0.0 is released 🎉 and this release includes this fix!

V-Orbit commented 5 years ago

Fantastic work @JaZo! I'll update the library immediately! thanks for your help 💓