Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonApiView doesn't use targetForeignKey, which causes incorrect results if that property is in use #191

Open
geoidesic opened this issue Jan 25, 2025 · 0 comments
Labels

Comments

@geoidesic
Copy link
Collaborator

E.g.

        $this->belongsToMany('Administratives', ['through' => 'PeopleAdministratives', 'className' => 'People', 'foreignKey' => 'person_id', 'targetForeignKey' => 'administrative_id']);
        $this->belongsToMany('AdministrativesClients', ['through' => 'PeopleAdministratives', 'className' => 'People', 'foreignKey' => 'administrative_id', 'targetForeignKey' => 'person_id']);

With GET request:

{{protocol}}{{domain}}/api/people/103c3b19-707f-4d3d-861b-000000000000/relationships/administratives

Will result in the relationship data providing the wrong column – i.e. person_id instead of the desired administrative_id

Required edit to JsonApiView.php

-        $result = $encoder->encodeIdentifiers($entity->get($association->getProperty()));
+        $relationshipData = $entity->get($association->getProperty());
+        
+        $transformedData = [];
+        if ($relationshipData) {
+            foreach ($relationshipData as $item) {
+                if (isset($item->_joinData)) {
+                    // Always use the targetForeignKey from the association
+                    $targetField = $association->getTargetForeignKey();
+                    if (isset($item->_joinData->{$targetField})) {
+                        $transformedItem = clone $item;
+                        $transformedItem->id = $item->_joinData->{$targetField};
+                        $transformedData[] = $transformedItem;
+                    }
+                }
+            }
+        }
+        
+        $result = $encoder->encodeIdentifiers($transformedData);
@geoidesic geoidesic added the bug label Jan 25, 2025
@geoidesic geoidesic changed the title Neomerx encoder doesn't use targetForeignKey, which causes incorrect results if that property is in use JsonApiView doesn't use targetForeignKey, which causes incorrect results if that property is in use Jan 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant