Keyword `with` is not working with Drizzle - Stack Overflow

admin2025-04-16  2

This is my Drizzle schema:

import { pgTable, text, integer, uuid, timestamp } from "drizzle-orm/pg-core"
import { relations } from "drizzle-orm"

export const userTable = pgTable("user", {
  id: uuid().defaultRandom().primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull().unique()
})

export const userToUserCredentialRelations = relations(userTable, ({ one }) => ({
  userCredential: one(userCredentialTable),
}))

export const userCredentialTable = pgTable("user_credential", {
  id: uuid().defaultRandom().primaryKey(),
  userId: uuid("user_id")
    .notNull()
    .unique()
    .references(() => userTable.id),
  passwordHash: text("password_hash").notNull(),
})

export const userCredentialToUserRelations = relations(userCredentialTable, ({ one }) => ({
  user: one(userTable, {
    fields: [userCredentialTable.userId],
    references: [userTable.id],
  }),
}))

When I query 1 user, I want to include userCredential nested.

you can see in the type of the User, there is no userCredential.

Also, this should drop an error,

Full code is Here.

From the Doc, I think I am doing the exact same thing

This is my Drizzle schema:

import { pgTable, text, integer, uuid, timestamp } from "drizzle-orm/pg-core"
import { relations } from "drizzle-orm"

export const userTable = pgTable("user", {
  id: uuid().defaultRandom().primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull().unique()
})

export const userToUserCredentialRelations = relations(userTable, ({ one }) => ({
  userCredential: one(userCredentialTable),
}))

export const userCredentialTable = pgTable("user_credential", {
  id: uuid().defaultRandom().primaryKey(),
  userId: uuid("user_id")
    .notNull()
    .unique()
    .references(() => userTable.id),
  passwordHash: text("password_hash").notNull(),
})

export const userCredentialToUserRelations = relations(userCredentialTable, ({ one }) => ({
  user: one(userTable, {
    fields: [userCredentialTable.userId],
    references: [userTable.id],
  }),
}))

When I query 1 user, I want to include userCredential nested.

you can see in the type of the User, there is no userCredential.

Also, this should drop an error,

Full code is Here.

From the Doc, I think I am doing the exact same thing

Share Improve this question edited Feb 3 at 21:40 Alan asked Feb 3 at 20:45 AlanAlan 10.2k4 gold badges58 silver badges75 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You need to switch where the "foreign key" is stored. Right now, you should be able to query userCredential with user but not User with UserCredential.

So swap it. Add userCredentialId column to users. And move the Drizzle relation to the user side.

Or just get the credential with user that would work too.

A unique constraint on userId column in userCredential is unnecessary.

转载请注明原文地址:http://www.anycun.com/QandA/1744750729a87090.html