How to work with Many to Many relationships (M2M) on Directus

Bianca
2 min readAug 12, 2022

--

As a reader in today’s world, recommendations and reviews are all over the internet and there is a large community of readers on social media.

Because of my love for books, and in collaboration with a booktoker, I developed this website for the community.

The idea is that the user can vote for a book in each award and this information is fetched from the CMS (Directus). Also, the user can vote for a book that was not already voted with a search bar connected to Google Books API.

To made that possible I had to create a collection of books and a collection of awards in my CMS but I needed to make a relationship.

I used a many to many relationship because one book could be voted in all awards and one award needed several books voted.

Create relationship

Once you created both collections add a field in one of them and select Relational/Many to Many, complete the key (A unique column name) and select the related collection.

Directus automatically is going to create the relationship collection. If you want to have the collection in Content make the collection visible clicking in the three dots.

The new collection is going to have three ids’: the junction collection id and the id’s of the two collection you relationed.

In my case, award field have the id of the award and book field have the id of the book. And as the purpose of all of this was to track the votes of a book in an award Iadded a votes field with an input of 0.

And this is the how it looks in Content tab:

If you are a reader and want to have fun check https://books-awards.vercel.app/

--

--