Skip to content

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

@geoidesic

Description

@geoidesic

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);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions