One-to-many relations
A user owns multiple posts or other child records.
Drizzle ORM · Function
many() defines a relation that returns multiple records from a target table. Configure it with source and target columns, and optionally an alias or filter.
Use r.many.<table> inside defineRelations to describe a relation whose result is an array of records from the target table. Provide the source and target columns with from and to; optional alias and where settings customize the relation.
r.many.<table>({ from, to, alias?, where? })| Name | Type | Description |
|---|---|---|
from | column reference | Source column that starts the soft relation. |
to | column reference | Target column in the related table. |
alias | string | Optional custom relation alias. |
where | object | Optional condition restricting related records. |
An array of objects from the target table when used as a many relation.
from to identify the source column where the soft relation starts.id column.to to identify the matching target column in the related table.import { defineRelations } from 'drizzle-orm';
const relations = defineRelations({ users, posts }, (r) => ({
users: {
feed: r.many.posts({
from: r.users.id,
to: r.posts.ownerId,
alias: 'custom_name',
where: { approved: true },
}),
},
}));Defines a feed relation that returns approved posts associated with each user.
A user owns multiple posts or other child records.
Records connect to multiple records through an association table.
Related results need a domain-specific property name.
Only qualifying related records should be returned.
r.many.posts represent?r.many.posts declares that the relation returns an array of records from posts, rather than one record. The relation is configured with source and target columns such as r.users.id and r.posts.ownerId.
Follow-up: How would you model many-to-many data? Use an explicitly defined junction table, or use the documented through form to select related records through that table.
from and to used for?from identifies the column where the soft relation begins, while to identifies the corresponding column on the target table. In the example, the relation starts at the users table's id and targets posts through ownerId.
Follow-up: What additional relation metadata can be supplied? An alias can customize the relation name, and a where object can constrain matching records.
The property assigned to the relation, such as feed, is a custom key exposed on the user object in relational queries. The target table and relation configuration determine the array's record type.
Follow-up: How can a relation be filtered? Add a where condition, such as { approved: true }, to constrain the related records.
defineRelationsonethroughjunction tablejoin table