Alan
Alan

Reputation: 10183

Keyword `with` is not working with Drizzle

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.

enter image description here

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

Also, this should drop an error,

enter image description here

Full code is Here.

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

Upvotes: 0

Views: 25

Answers (1)

codestomping
codestomping

Reputation: 173

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.

Upvotes: 1

Related Questions