Search code examples
nestedmany-to-manyone-to-manystrapi

How to create one-to-many and many-to-many relations in Strapi v.4?


I want to create relations between Post and Tag as follows.

  1. Post has many Tags (one-to-many)
  2. Tags have and belongs to many Posts (many-to-many)

I created collection types for Post and Tag.

enter image description here

enter image description here

Set them accessible for public user.

enter image description here

enter image description here

enter image description here

I created 1 post with 3 tags.

Now, when I try to see them at http://localhost:1337/api/posts I don’t see nested elements, i.e. tags… Am I missing anything ?

enter image description here

And lastly, I was not able to create Many-to-Many relations between Post and Tag with the following error. I understand that Tags field already exists, but I thought this is how supposed to be set.

enter image description here


Solution

  • I got reply from Strapi forum, so decided to share here.

    https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/populating-fields.html

    According to the docs above, to pull (in my case) 1st level nested elements I have to add populate[0] parameter like so:

    http://localhost:1337/api/posts?populate[0]=tags

    enter image description here