taylor.presto
Explore posts from serversDTDrizzle Team
•Created by taylor.presto on 11/5/2024 in #help
How do I get types for relationship queries?
// Users table
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', { length: 255 }).notNull().unique(),
name: text('name').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull()
});
// Todos table
export const todos = pgTable('todos', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 255 }).notNull(),
completed: boolean('completed').default(false).notNull(),
userId: integer('user_id').references(() => users.id).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull()
});
// Define the relationships
export const usersRelations = relations(users, ({ many }) => ({
todos: many(todos)
}));
export const todosRelations = relations(todos, ({ one }) => ({
user: one(users, {
fields: [todos.userId],
references: [users.id],
})
}));
// Example usage:
const db = drizzle(client);
// Query user with their todos
const userWithTodos = await db.query.users.findFirst({
where: (users, { eq }) => eq(users.id, newUser[0].id),
with: { // HOW DO I GET THESE TYPES?
todos: true
}
});
I want to do something like this, but I want to be able to pass a type for my relationships so I know what can be passed in.
getUserById = (id, relationships?) => {
await db.query.users.findFirst({
where: (users, { eq }) => eq(users.id, newUser[0].id),
...(relationships ? { with: relationships } : {})
});
}
// Users table
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', { length: 255 }).notNull().unique(),
name: text('name').notNull(),
createdAt: timestamp('created_at').defaultNow().notNull()
});
// Todos table
export const todos = pgTable('todos', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 255 }).notNull(),
completed: boolean('completed').default(false).notNull(),
userId: integer('user_id').references(() => users.id).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull()
});
// Define the relationships
export const usersRelations = relations(users, ({ many }) => ({
todos: many(todos)
}));
export const todosRelations = relations(todos, ({ one }) => ({
user: one(users, {
fields: [todos.userId],
references: [users.id],
})
}));
// Example usage:
const db = drizzle(client);
// Query user with their todos
const userWithTodos = await db.query.users.findFirst({
where: (users, { eq }) => eq(users.id, newUser[0].id),
with: { // HOW DO I GET THESE TYPES?
todos: true
}
});
I want to do something like this, but I want to be able to pass a type for my relationships so I know what can be passed in.
getUserById = (id, relationships?) => {
await db.query.users.findFirst({
where: (users, { eq }) => eq(users.id, newUser[0].id),
...(relationships ? { with: relationships } : {})
});
}
2 replies