Relations field: use another field instead ID, for post/put requests

System Information
  • Strapi Version: 4.5.1
  • Operating System: windows
  • Database: MySql
  • Node Version: 16.13.2
  • NPM Version: 8.1.2

Hola everyone, thanks for reading me :slight_smile:

I have one issue with relations field. As far i know, you need to introduce the id of the element that you want have the relation. The problem is that i don’t want have the id, i need another field.
Let’s say that i have two collections:

Country - Language

Inside countries we have:

  • Id : autoincremental generated by Strapi.
  • Name: string field with the name of the country.
  • Languages: relation field.

Inside languages we have:

  • Id : autoincremental generated by Strapi.
  • Name: string field with the name of the language.
  • ISO639: string field refered to the language iso639

So… for example, making a PUT with this url: …/api/countries/1
Request:

{
    "data": {
        "id": 11,
        "name": "Germany",
        "languages": ["de"]
    }
}

I don’t know how to achieve this, usually i don’t post in forums/stackoverflow because usually i’m good researcher, but in this case… i didn’t find anything important.

Have a good day!


I forget to mention that i did this steps, in order to change my configuration regarding field into relations: Relation selection field is showing IDs instead of names - #4 by rania

1 Like

Where you able to do it? I’ve looking for a solution but nothing yet…

After going through the hunt, I got tired and did a workaround.
You can instead make a GET request to every field in the “languages” collection and get the id and name associated with the fields like this:
let mappedLanguages = ;
for(i = 0; i < collection.length; i++) {
API call
mappedLanguages.push({id, name})
}

And now when you want to relate, instead of id, use the mappedLanguages array and find the id associated with the name you want to use, like this:
data: {
languages: mappedLanguages.find(lng => lng.name == “<Your_string>”)?.id
}

This works for me, I’m solving a problem by creating a problem but hey, it’s better than spending hours to find a way, how to refer another field instead of ids