FriendsOfCake / crud-json-api

Build advanced JSON API Servers with almost no code.
https://crud-json-api.readthedocs.io/
MIT License
56 stars 32 forks source link

Related link does gives 404 for manyToOne custom association #155

Closed geoidesic closed 3 years ago

geoidesic commented 3 years ago

Given a people and enquiries table:

$this->table('enquiries', ['id' => false, 'primary_key' => ['id']])
            ->addColumn('created', 'datetime', [
                'default' => 'CURRENT_TIMESTAMP',
                'limit' => null,
                'null' => true,
            ])
            ->addColumn('id', 'uuid', [
                'default' => null,
                'limit' => null,
                'null' => false,
            ])
            ->addColumn('notary_id', 'uuid', [
                'comment' => 'Notary responsible for taking this enquiry forward (and for billing), not necessarily the same as logged in user',
                'default' => null,
                'limit' => null,
                'null' => false,
            ])
...
 $this->table('people', ['id' => false, 'primary_key' => ['id']])
            ->addColumn('id', 'uuid', [
                'default' => null,
                'limit' => null,
                'null' => false,
            ])

I wish to associate enquiries.notary_id to person.id as a manyToOne. In order to do so, I have the following association on the EnquiriesTable:

        $this->belongsTo('Notaries', ['className' => 'People', 'foreignKey' => 'notary_id']);

This partly works – but the links provided via JSONAPI are not all valid:

 "notary": {
                "links": {
                    "self": "/api/enquiries/73ac53d0-3fdb-4300-bc6c-09b9e534cced/relationships/notary",
                    "related": "/api/enquiries/73ac53d0-3fdb-4300-bc6c-09b9e534cced/notary"
                },

It looks like something is wrong with the association reverse lookup. Looking deeper, it seems to be that if one is using an aliased foreignKey then the association is not picked up and listed in $table->_associations. So this may be a deeper problem with Cake itself.

geoidesic commented 3 years ago

Looks like the reverse association on PeopleTable was missing:

        $this->hasMany('NotaryEnquiries', ['className' => 'Enquiries', 'foreignKey' => 'notary_id']);