How to make all relations be deleted when user is removed?

Hello! I'm trying to get my head around for table relations, and just can't seem to get this figured out. I've table for users, and user sessions. When I'm trying to delete a user, postgres throws error, that delete violates foreign key constraint on sessions. What might be proper way to define this relations? Below is my schema.
export const users = createTable(
"user",
{
id: serial("id").primaryKey(),
email: varchar("email", { length: 256 }).unique().notNull(),
password: varchar("password", { length: 256 }).notNull(),
role: userRoleEnum("role").notNull(),
firstName: varchar("first_name", { length: 256 }),
lastName: varchar("last_name", { length: 256 }),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at"),
deletedAt: timestamp("deleted_at"),
passwordResetToken: varchar("password_reset_token", {
length: 256,
}),
passwordResetTokenExpiresAt: timestamp("password_reset_token_expires_at", {
withTimezone: true,
mode: "date",
}),
allowLogin: boolean("allow_login").default(true).notNull(),
},
(table) => ({
emailIndex: index("email_idx").on(table.email),
}),
);

export const sessions = createTable("session", {
id: varchar("id", {
length: 255,
}).primaryKey(),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expiresAt: timestamp("expires_at", {
withTimezone: true,
mode: "date",
}).notNull(),
});
export const users = createTable(
"user",
{
id: serial("id").primaryKey(),
email: varchar("email", { length: 256 }).unique().notNull(),
password: varchar("password", { length: 256 }).notNull(),
role: userRoleEnum("role").notNull(),
firstName: varchar("first_name", { length: 256 }),
lastName: varchar("last_name", { length: 256 }),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at"),
deletedAt: timestamp("deleted_at"),
passwordResetToken: varchar("password_reset_token", {
length: 256,
}),
passwordResetTokenExpiresAt: timestamp("password_reset_token_expires_at", {
withTimezone: true,
mode: "date",
}),
allowLogin: boolean("allow_login").default(true).notNull(),
},
(table) => ({
emailIndex: index("email_idx").on(table.email),
}),
);

export const sessions = createTable("session", {
id: varchar("id", {
length: 255,
}).primaryKey(),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expiresAt: timestamp("expires_at", {
withTimezone: true,
mode: "date",
}).notNull(),
});
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server