Directus Basics Part 2 — Understanding Relationships (M2O, O2M, M2M)
This is part two of our Directus Basics series. In part one , we set up a Directus instance and created our first collection. Today we're covering one of the most powerful features Directus offers: relationships between collections. By the end of this article, you'll understand three core relationship types — Many to One (M2O), One to Many (O2M), and Many to Many (M2M). There's a fourth type,…
In this second installment of Directus Basics, we delve into the powerful feature of relationships between collections. By understanding the three core relationship types — Many to One (M2O), One to Many (O2M), and Many to Many (M2M) — you'll gain a solid foundation for managing interconnected data in your Directus instance.
To begin, we create a new collection called "branding" and add default fields such as "name" (a basic input string) and "description" (a text area). After populating the collection with a few entries, we move on to establishing M2O relationships. In this case, products belong to a single brand, so we create a field named "brand_id" that links to the "branding" collection. By opting not to enable the create button, we ensure that brands are always chosen from an existing list.
Next, we set up the reverse relationship, O2M, by adding a field named "products" to the "branding" collection. This field references the "products" collection through the previously created "brand_id" field. Deactivating the create button on this side ensures that only brands with existing products are displayed.
The M2M relationship, which stands for Many to Many, presents a unique challenge. Both the "products" and "tags" collections can contain many related records. To illustrate this, we create a "tags" collection with fields for "name" and "description." We then associate products with tags by creating a "tags" field in the "products" collection.
This field, named "tags," establishes the M2M relationship. By opting out of the create button and using the advanced field creation mode, Directus automatically generates the reverse relationship on the "tags" collection. As a result, when a product is tagged, the corresponding products are linked to the tags without the need for manual intervention.
Understanding these relationship types is crucial for effectively managing data in Directus. By implementing these relationships in your own instance, you'll gain hands-on experience with this powerful feature and elevate your Directus skills. This concludes Part 2 of our Directus Basics series, with Part 3 focusing on Directus permissions. Stay tuned for more insights and tutorials, or check out the accompanying video on YouTube.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.