json-api
json-api copied to clipboard
Fix for included collection with numeric keys
When using the Resource Collection, if you have a relationship that is a HasOne or BelongsTo, and the keys are numeric, the flattened include map has keys associated with it.
This only happens with numeric keys, and does not happen when the keys are strings (as in all test cases)
Example: User -> HasOne? -> License
Without values() called, you'll end up with a keyed included response:
"included": {
"0": {
"id": "1",
"type": "basicModels",
"attributes": {
"url": "https://example.com/avatar1.png"
},
"relationships": {},
"meta": {},
"links": {}
},
"2": {
"id": "2",
"type": "basicModels",
"attributes": {
"url": "https://example.com/avatar2.png"
},
"relationships": {},
"meta": {},
"links": {}
}
},
This can be solved by getting only the values() from the collection.
You'll see that this does not occur when making a single resource, because values is already called on the included method:
https://github.com/timacdonald/json-api/blob/main/src/JsonApiResource.php#L170
https://github.com/timacdonald/json-api/blob/c3f89eef3e6c3e6b4f46321211543acc99f5134f/src/Concerns/Relationships.php#L55
Thanks for the PR Sam. I'll be digging back into this package development next week, so I'll review early next week and get this merged for ya. Thank you so much for sending through a test ❤️
No problem.
I was wrong in my ending sentence, and just discovered the same problem on the JsonAPIResource, https://github.com/timacdonald/json-api/blob/main/src/JsonApiResource.php#L170
I'll update and write another test soon
Fixed, although I believe this one has to do with a circular reference. idk, but it's fixed and tested
@timacdonald any update?
Running into this same issue in our project. Re-keying the array index with the Collection's values() method resolves our issues. Looking forward to seeing this merged in.
Thanks @snellingio and sorry for the delay. This will be tagged in the upcoming v1 release. There is beta already tagged.