-
Hi, I was searching the docs on how to create nullable one-to-many relationships and I've asked the bot for help. This was it's answer: ////// In Drizzle ORM, you can define optional relationships in a one-to-many context by allowing the foreign key on the "many" side to be nullable. This means that the foreign key column can contain null values, indicating that the relationship is optional. Here's an example of how to set up an optional one-to-many relationship in Drizzle ORM, where the foreign key in the "many" side might be null: import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name'),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
content: text('content'),
// authorId is nullable, indicating an optional relationship
authorId: integer('author_id').references(() => users.id).nullable(),
});
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
})); In this example:
By allowing ///// The nullable() method doesn't exist in the docs and is not suggested in vscode intellisense. How can I define such a relation in drizzle? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 3 replies
-
got the same problem |
Beta Was this translation helpful? Give feedback.
-
I got same problem |
Beta Was this translation helpful? Give feedback.
-
I deleted my database/restarted my migrations then created my initial migration and I don't have this problem anymore. I didn't change my schemas/relations. Using the latest beta version. I'm kinda confused about this. Still the 'help' bot is not working properly. All those A.I help bots are a waste of time for anything more than trivial answers 🤷♂️. The example is working fine: |
Beta Was this translation helpful? Give feedback.
-
Same problem. On drizzle-kit v0.23.0 and drizzle-orm v0.32.1. The generated SQL for a one-to-many relation includes In the schema: In the docs here, an example shows explicitly setting a foreign key to notNull().
|
Beta Was this translation helpful? Give feedback.
-
Any fixes for uuid's? I want the xxx_id in YYY to be nullable Example:
|
Beta Was this translation helpful? Give feedback.
That worked. Here's the generated sql from the migration: