Many-to-Many in Keel
How do I do many-to-many relationships in Keel?
In Keel schema design, many-to-many relationships are established by creating an intermediary model that includes fields referencing the two models you wish to link. This intermediary model acts as a bridge, allowing each of the original models to have multiple associations with the other.
Let's consider an example with two models: Author
and Book
. To create a many-to-many relationship between these, you would introduce a third model, perhaps named AuthorBook
. This model would contain references to both the Author
and Book
models. Here's how you would structure it:
- Define the
Author
andBook
models with their respective fields. - Create the
AuthorBook
model with two fields: one referencing theAuthor
and the other referencing theBook
. - In the
AuthorBook
model, these reference fields are crucial for establishing the many-to-many relationship.
Here's a basic schema illustrating this:
keel1model Author { 2 fields { 3 name Text 4 books AuthorBook[] 5 } 6 // ... actions and permissions 7} 8 9model Book { 10 fields { 11 title Text 12 authors AuthorBook[] 13 } 14 // ... actions and permissions 15} 16 17model AuthorBook { 18 fields { 19 author Author 20 book Book 21 } 22 // ... actions and permissions 23}
In this schema:
Author
andBook
each have a one-to-many relationship withAuthorBook
.AuthorBook
has two many-to-one relationships, one withAuthor
and one withBook
.- Together, these relationships form a many-to-many link between
Author
andBook
.
For further development of your schema, visit https://console.keel.so. Additionally, you can use the Keel CLI to interact with your schema and join the Keel Discord server at https://keel.so/discord for community support and queries.
Validate the schema
The provided schema is valid with no errors. You can confidently use this schema for establishing many-to-many relationships in Keel.
Remember, for further development of your schema, you can visit https://console.keel.so. Also, consider using the Keel CLI for schema interaction and join the Keel Discord community at https://keel.so/discord for any support or queries.