Many-to-Many
A many-to-many relation links many rows on one side to many rows on the other, such as posts carrying tags. Neither side can hold the link in a single column, so the ORM stores it in a separate join table.
Definition
The owning side declares tags: Tag[] without @via; the inverse uses posts: Post[] @via(tags).
The join table is derived from the declaration:
- The table name is
_Model_field, soPost.tagsproduces_Post_tags. It has two columns,sourceIdpointing at the owning model andtargetIdat the other one; in_Post_tagsthey point atPostandTag. - Both columns form the primary key, so the same pair cannot be linked twice.
Example
ts
model Post {
id: int @id @auto
title: string
tags: Tag[]
}
model Tag {
id: int @id @auto
name: string @unique
posts: Post[] @via(tags)
}1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Both sides support collection queries and nested relation operations, but not nested createMany; see Relation Writes:
ts
await db.post.findMany({
where: { tags: { some: { name: "typescript" } } },
include: { tags: true },
});
await db.post.create({
data: { title: "Hello", tags: { connect: [{ id: 1 }] } },
});1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Notes
- The owning array field takes no attributes:
@via,@unique, and@relationare not allowed on it. - When the link itself carries data such as a role or a join date, connect the two sides through an ordinary model instead; see Associations with Extra Fields.
- Both models must have a single-field primary key, because the join table stores both keys as plain columns.
Next Steps
- Associations with Extra Fields: a join model that carries its own data
- Referential Actions: what happens when a linked row is deleted