Explaining the differences between .references() and relations function

Hi I'm a bit unclear in the example why the comments table in this example does not use the .references() function on the author id field. Is this because the .relations() method and relations({one}) are achieveing the same thing but two different approaches? https://orm.drizzle.team/docs/rqb#one-to-many
...

export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
content: text('content'),
authorId: integer('author_id'),
});

export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
comments: many(comments)
}));

export const comments = pgTable('comments', {
id: serial('id').primaryKey(),
text: text('text'),
authorId: integer('author_id'),
postId: integer('post_id'),
});

export const commentsRelations = relations(comments, ({ one }) => ({
post: one(posts, {
fields: [comments.postId],
references: [posts.id],
}),
}));
...

export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
content: text('content'),
authorId: integer('author_id'),
});

export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
comments: many(comments)
}));

export const comments = pgTable('comments', {
id: serial('id').primaryKey(),
text: text('text'),
authorId: integer('author_id'),
postId: integer('post_id'),
});

export const commentsRelations = relations(comments, ({ one }) => ({
post: one(posts, {
fields: [comments.postId],
references: [posts.id],
}),
}));
Drizzle Queries - Drizzle ORM
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
3 Replies
Angelelz
Angelelz13mo ago
Yes, the answer is a little further down in that link: https://orm.drizzle.team/docs/rqb#foreign-keys
Drizzle Queries - Drizzle ORM
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
Sam
SamOP13mo ago
Hi @Angelelz so to clarify .references() creates a foreign key constraint but relations does not? But they can also work fairly interchangably in databases that support foreign key contraints.
Angelelz
Angelelz13mo ago
The answer to the first part of your question is yes. But defining relations won't create foreign key constrains in the database. This was done on purpose to support database provider like planetscale that don't support foreign keys
Want results from more Discord servers?
Add your server