How do I fetch data with M2M relationships?
In Directus, fetching many-to-many (M2M) relationships involves understanding how they are structured and how to query them via the REST or GraphQL API. M2M relationships are configured with a junction table that is exposed at the API level. If we assume the following ingredients
,recipes
and recipes_ingredients
collection exist with an M2M
field on recipes
names ingredients
we can query for the ingredient names as follows:
Fetching M2M Relationships via REST API
To fetch a recipe along with the name of its ingredients:
GET /items/recipes?fields=*,ingredients.ingredients_id.name
Where:
*
fetches all top level fieldsingredients
is the alias set up in the relationship field inrecipes
.ingredients_id.name
fetches the name fields for the relatedingredients
collection only.
Example JSON Response
{
"data": [
{
"id": 1,
"name": "Recipe 1",
"ingredients": [
{
"ingredients_id": {
"name": "Ingredient 1"
}
},
{
"ingredients_id": {
"name": "Ingredient 2"
}
}
]
}
]
}
GraphQL Equivalent
If you’re using GraphQL, the query would look like:
query {
recipes {
id
name
ingredients {
ingredients_id {
name
}
}
}
}