Fuzbo
Fuzbo
Explore posts from servers
DTDrizzle Team
Created by Fuzbo on 5/26/2023 in #help
Many-to-Many Self Relation
I'm looking to migrate from Prisma, but I'm having trouble trying to figure out how a many-to-many self relation should be defined. The prisma schema I has previously was similar to:
model User {
id String @id
email String? @unique
followers User[] @relation("UserFollows")
following User[] @relation("UserFollows")
}
model User {
id String @id
email String? @unique
followers User[] @relation("UserFollows")
following User[] @relation("UserFollows")
}
Currently my schema looks like:
export const user = mysqlTable(
"User",
{
id: varchar("id", { length: 191 }).primaryKey().notNull(),
email: varchar("email", { length: 191 }),
},
({ email }) => ({ emailKey: uniqueIndex("User_email_key").on(email) }),
);

export const userRelations = relations(user, ({ one, many }) => ({
account: one(account, {
fields: [user.id],
references: [account.userId],
}),
cosmetics: many(cosmeticToUser),
followers: many(userFollows),
following: many(userFollows),
}));

export const userFollows = mysqlTable(
"_UserFollows",
{
userId: varchar("A", { length: 191 }).notNull(),
followedBy: varchar("B", { length: 191 }).notNull(),
},
({ userId, followedBy }) => ({
pk: primaryKey(userId, followedBy),
abUnique: uniqueIndex("_UserFollows_AB_unique").on(userId, followedBy),
followedByIdx: index("_UserFollows_B_index").on(followedBy),
}),
);

export const userFollowsRelations = relations(userFollows, ({ one }) => ({
user: one(user, {
fields: [userFollows.userId],
references: [user.id],
}),
}));
export const user = mysqlTable(
"User",
{
id: varchar("id", { length: 191 }).primaryKey().notNull(),
email: varchar("email", { length: 191 }),
},
({ email }) => ({ emailKey: uniqueIndex("User_email_key").on(email) }),
);

export const userRelations = relations(user, ({ one, many }) => ({
account: one(account, {
fields: [user.id],
references: [account.userId],
}),
cosmetics: many(cosmeticToUser),
followers: many(userFollows),
following: many(userFollows),
}));

export const userFollows = mysqlTable(
"_UserFollows",
{
userId: varchar("A", { length: 191 }).notNull(),
followedBy: varchar("B", { length: 191 }).notNull(),
},
({ userId, followedBy }) => ({
pk: primaryKey(userId, followedBy),
abUnique: uniqueIndex("_UserFollows_AB_unique").on(userId, followedBy),
followedByIdx: index("_UserFollows_B_index").on(followedBy),
}),
);

export const userFollowsRelations = relations(userFollows, ({ one }) => ({
user: one(user, {
fields: [userFollows.userId],
references: [user.id],
}),
}));
I'm just not quite sure how to construct the relations properly for the self-referencing with the many-to-many relation.
69 replies