I'm using Drizzle ORM with PostgreSQL, and this is how my schema looks. In a simple manner, there is a 'users' table and a 'contacts' table. Each user can have multiple contacts.
export const users = pgTable("users", {
id: uuid("id").defaultRandom().primaryKey(),
email: text("email").unique().notNull(),
about: varchar("about", { length: 100 }),
created_at: timestamp("created_at").defaultNow(),
workspace_id: uuid("workspace_id").references(() => workspaces.id, {
onDelete: "cascade",
onUpdate: "cascade"
})
});
export const usersRelations = relations(users, ({ one, many }) => ({
permission: one(permissions, {
fields: [users.email],
references: [permissions.user_email]
}),
contacts: many(contacts,{
relationName: 'users_contacts',
})
}));
export const contactType = pgEnum(....);
export const contacts = pgTable("contacts", {
id: uuid("id").defaultRandom().primaryKey(),
type: contactType("type").default("phone").notNull(),
value: text("value").notNull(),
created_at: timestamp("created_at").defaultNow(),
user_email: text("user_email")
.references(() => users.email, {
onDelete: "cascade",
onUpdate: "cascade"
})
.unique()
.notNull()
});
export const contactsRelations = relations(contacts, ({ many }) => ({
users: many(users)
}));
but when i do like this
const workspaceUsers = await db.query.users.findMany({
where: eq(users.workspace_id, loggedWorkspace.data.id),
with: {
permission:true,
contacts: true
}
});
However, I don't know why I'm encountering this error. Please let me know how I can fix it.
⨯ Internal error: Error: There is not enough information to infer relation "users.contacts"
Okay so basically I was doing it in wrong way, I just need to use relationName on both side like this
export const usersRelations = relations(users, ({ man }) => ({
contacts: many(contacts, {
relationName: "users_contacts"
})
}));
export const contactsRelations = relations(contacts, ({ one }) => ({
user: one(users, {
fields: [contacts.user_email],
references: [users.email],
relationName: "users_contacts"
})
}));