example on users table with followers and follows?

I need
1 Reply
Fyzz
Fyzz9mo ago
Someone may have a better one but this is how id do it
export const users = mysqlTable("users", {
id: serial("id").autoincrement().primaryKey(),
// other user data
});

export const usersRelations = relations(users, ({ many }) => ({
following: many(follows),
followers: many(follows),
}));


export const follows = mysqlTable("follows", {
id: serial("id").autoincrement().primaryKey(),
follower_user_id: int("follower_user_id").notNull(),
following_user_id: int("following_user_id").notNull(),
followed_at: timestamp("followed_at").defaultNow(),
// other follow data
});

const followsRelations = relations(follows, ({ one }) => ({
follower: one(users, {
fields: [follows.follower_user_id],
references: [users.id],
}),
following: one(users, {
fields: [follows.following_user_id],
references: [users.id],
}),
}));
export const users = mysqlTable("users", {
id: serial("id").autoincrement().primaryKey(),
// other user data
});

export const usersRelations = relations(users, ({ many }) => ({
following: many(follows),
followers: many(follows),
}));


export const follows = mysqlTable("follows", {
id: serial("id").autoincrement().primaryKey(),
follower_user_id: int("follower_user_id").notNull(),
following_user_id: int("following_user_id").notNull(),
followed_at: timestamp("followed_at").defaultNow(),
// other follow data
});

const followsRelations = relations(follows, ({ one }) => ({
follower: one(users, {
fields: [follows.follower_user_id],
references: [users.id],
}),
following: one(users, {
fields: [follows.following_user_id],
references: [users.id],
}),
}));
then add the uniqe indexes / indexes for your querying needs, probably the follower_user_id and following_user_id and to prevent overlapping follows follower_user_id the id of the user who doing the following (currentUser) following_user_id the id of the user being followed