I would like to know how I should update many-to-many relationships in my API.
My app has companies
that can have many tools
and technologies
. The relationship is stored in joining tables companies_technologies
and companies_tools
.
The frontend has a form to edit the company. I would like the users to submit a single form to update (1) company info, (2) the tools, and (3) technologies.
My solution is to send PUT
request to the server with the following data:
{
...company attributes...,
tool_ids: [1,2,3,4],
technology_ids: [11,22,33,44]
}
Then in the server, I would find all tools that belong to the company, get their ids, find the difference between those ids and tool_ids
, and insert/delete to companies_tools
table. Same for technology_ids
.
But such an approach feels kind of clunky. Is there an alternative approach, or how can I improve my solution?
Best Answer
Nothing clunky about this. Just straight up send the data to update with. Though I'm making a few assumptions:
I'm going to just assume the "tools" you're referring to are what you labeled "communication methods".
I'm assuming when sending this PUT, tech and tools are constrained to existing id's. Meaning if the user wants to add a new tool when typing you either disallow this or send a different rest update to create the tool, learn its id, and use that new id in this PUT.