A one-to-many relation allows one record to be associated with multiple records in another collection. If you define the relation on both sides (inversed), the library automatically synchronizes them.
One-to-many
posts.defineRelations(({ many }) => ({
comments: many(comments),
}))
Inversed (Two-way) relations
When both collections define relations to each other, updating one side automatically updates the other. For example, adding a comment to a post will automatically set the post property on that comment.
posts.defineRelations(({ many }) => ({
comments: many(comments),
}))
comments.defineRelations(({ one }) => ({
post: one(posts),
}))
const postSchema = z.object({
get comments() {
return z.array(commentSchema)
},
})
const commentSchema = z.object({
text: z.string(),
get post() {
return postSchema
},
})
const posts = new Collection({ schema: postSchema })
const comments = new Collection({ schema: commentSchema })
posts.defineRelations(({ many }) => ({
comments: many(comments),
}))
comments.defineRelations(({ one }) => ({
post: one(posts),
}))