directus / v8-archive

Directus Database API β€” Wraps Custom SQL Databases with a REST/GraphQL API
https://docs.directus.io/api/reference.html
505 stars 204 forks source link

Create Many-to-Many (or any other relations) in the same API call to create item #2051

Open abuzahran opened 4 years ago

abuzahran commented 4 years ago

Hi All - Not sure if this is a bug or just a questions so apologies in advance if this is the wrong place.

Expected Behaviour:

I have two collections:

(a) Staff (b) roles

There is a many to many relationship between (a) & (b) through a junction table "staff_roles". i.e. one staff can have multiple roles. When I extract the items via API from staff table with

'fields=.'

parameter then I get the roles from the junction table which is great.

Now, I want to create an item in Staff collection via rest api and I want to be able to create the roles (many to many relation) in the same API call. Is it possible ?

Actual Behaviour

But when I make the POST as shows in the screenshot then it throws the below error:

{ "error": { "code": 13, "message": "Invalid or Empty Payload" } }

directus

I have also tried without the primary key for the relation:

directus 2

benhaynes commented 4 years ago

Hey @abuzahran β€” we're a bit slammed at the moment, but @rijkvanzanten can confirm the syntax for saving relational items with the API when he has some time to take a break from v9. To be clear, these staff and roles already exist... you're just trying to link them?

abuzahran commented 4 years ago

Hey @benhaynes thanks for the quick comment.

To be clear, these staff and roles already exist... you're just trying to link them?

Roles items exist. I just want to be able to link these Existing roles with a β€œnew” staff item that I want to create via api.

i.e.

Post to /project/staff (create new staff item)

Name: xxxx Address: xxxxx Roles: existing role 1 Existing role 2 Existing roles 3

I hope it makes sense.

Thanks a lot

abuzahran commented 4 years ago

Hi @rijkvanzanten I know you are extremely busy but would you be able to please assist with my query? Thanks

rijkvanzanten commented 4 years ago

@abuzahran the screenshots you post look right to me. The no payload error indicates that the API didn't receive the body correctly at all. Could you verify you use the Content-Type: application/json header?

abuzahran commented 4 years ago

@rijkvanzanten Thanks yes it does have the header (Sorry for late response)

rijkvanzanten commented 4 years ago

Ha, I answered within a day to your question, you took 56 πŸ˜‚ (jk jk, we all get busy πŸ˜‰ )

Are you able to "properly" use the admin app? I'm asking as the admin app itself uses the same endpoints, so if the m2m interface in there works, we know for a fact that it has to work through the API directly as well, which means there's something going sideways in the way we're testing the endpoint