Skyler
Skyler
DTDrizzle Team
Created by Skyler on 6/4/2023 in #help
Many to many relationship between one type
I'm making an application where I have users who are able to follow other users. This means that I need a many-to-many relationship, but both sides are the same type (a user). I'm not sure how to express this with drizzle's relations, as I'm not sure how to specify both sides of the relationship For example...
export const Users = pgTable("users", {
id: uuid('id').primaryKey().defaultRandom(),
});

export const UsersRelations = relations(Users, ({ many }) => ({
followers: many(Followers), // how do I separate these?
following: many(Followers), // is it even possible?
}))

export const Following = pgTable("followers", {
userId: uuid('user_id').references(() => Users.id).notNull(),
followingId: uuid('following_id').references(() => Users.id).notNull(),
}, (table) => ({
cpk: primaryKey(table.userId, table.followingId)
}));

export const FollowingRelations = relations(Following, ({ one }) => ({
user: one(Users, {
fields: [Following.userId],
references: [Users.id],
}),
following: one(Users, {
fields: [Following.followingId],
references: [Users.id],
})
}))
export const Users = pgTable("users", {
id: uuid('id').primaryKey().defaultRandom(),
});

export const UsersRelations = relations(Users, ({ many }) => ({
followers: many(Followers), // how do I separate these?
following: many(Followers), // is it even possible?
}))

export const Following = pgTable("followers", {
userId: uuid('user_id').references(() => Users.id).notNull(),
followingId: uuid('following_id').references(() => Users.id).notNull(),
}, (table) => ({
cpk: primaryKey(table.userId, table.followingId)
}));

export const FollowingRelations = relations(Following, ({ one }) => ({
user: one(Users, {
fields: [Following.userId],
references: [Users.id],
}),
following: one(Users, {
fields: [Following.followingId],
references: [Users.id],
})
}))
In the example above, the UserRelations relation needs to have many follower relations twice, but it needs to be one for each side of the relationship. I'm not sure how to specify that these are different
export const UsersRelations = relations(Users, ({ many }) => ({
followers: many(Followers), // how do I separate these?
following: many(Followers), // is it even possible?
}))
export const UsersRelations = relations(Users, ({ many }) => ({
followers: many(Followers), // how do I separate these?
following: many(Followers), // is it even possible?
}))
20 replies