Mayanktaker
Mayanktaker

Reputation: 325

Directus - how to show Many2Many relationship in api

I am trying to make a blog in Directus. I created Blog Collection and Categories Collection. I am using junction table with many to many relationship to connect categories to blog. I can create a new blog post and select category from category collection and I can add a new category also. But when I am calling in api, it is not showing the category field in my rest api call. I can call category endpoint and view the list of all the categories in rest api but in blog collection endpoint, I cant view related category name.

I want to view all the selected category name to each blog posts in my rest api. And I want to view all the blog posts when I call category collection in my rest api by putting category name like projectname/items/categories/aliens/ so I can see all the blog posts of aliens categories.

Currently I am getting this by calling my blog collection in json -

{
  "data": [
    {
      "id": 1,
      "status": "published",
      "owner": 1,
      "created_on": "2020-03-16 21:15:25",
      "blog_title": "first blog post title",
      "blog_content": "<p>sdlkjfhsdkfol8ysdmfhj sd,fh klsdhf msoiudf oihsdyfghm soreht4,7shetc,oiuh,scenclkr</p>\n<p><strong>dsfgdsfgds</strong></p>"
    }
  ]
}

How to get the category name on rest api ?

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Upvotes: 4

Views: 9576

Answers (3)

Daniel Fanica
Daniel Fanica

Reputation: 450

You should have a relational table created between those 2 tables so you should be able to filter the information like this ?fields=id,blog_title,blog_content,category.category_id.category_name,category.category_id.status

In case this is confusing let me try to simplify the relationship part:

category.category_id.category_name
<field_name_on_current_item>.<identifier_on_junction_table_related_to_category_id>.<relation_field_name_to_display>

I realise that this is an old post, but it might help someone looking for the answer.

Upvotes: 7

Robert
Robert

Reputation: 694

To select only the relational data use

?fields=category.*

This shows only the related category field of the blog article.

Upvotes: 4

RANGER
RANGER

Reputation: 1691

Did you try using the fields parameter? This is used to fetch deeply nested relational data:

?fields=*.*.*

In this example, the asterisk is a wildcard for_all_ fields at that relational depth... so this fetches three levels deep.

https://docs.directus.io/api/query/fields.html

Upvotes: 16

Related Questions