many to many relation to same table with one relation field

I would like to depict the following scenario. There is a table “Avatars” which has a relation “Friends” that refers to itself, i.e. the table “Avatars”. Something like that:
xport const avatars = pgTable("avatars", {
id: text().primaryKey().default(sql`gen_random_uuid()`).notNull(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
name: text().notNull(),
});

export const avatarsRelations = relations(avatars, ({ many }) => ({
friends: many(avatarsToFriends),
}));

export const avatarsToFriends = pgTable(
'avatars_to_friends',
{
avatarId: text()
.notNull()
.references(() => avatars.id),
friendId: text()
.notNull()
.references(() => avatars.id),
},
(t) => ({
pk: primaryKey({ columns: [t.avatarId, t.friendId] }),
}),
);

export const avatarsToFriendsRelations = relations(avatarsToFriends, ({ one }) => ({
friend: one(avatars, {
fields: [avatarsToFriends.friendId],
references: [avatars.id],
}),
avatar: one(avatars, {
fields: [avatarsToFriends.avatarId],
references: [avatars.id]
}),
}));
xport const avatars = pgTable("avatars", {
id: text().primaryKey().default(sql`gen_random_uuid()`).notNull(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
name: text().notNull(),
});

export const avatarsRelations = relations(avatars, ({ many }) => ({
friends: many(avatarsToFriends),
}));

export const avatarsToFriends = pgTable(
'avatars_to_friends',
{
avatarId: text()
.notNull()
.references(() => avatars.id),
friendId: text()
.notNull()
.references(() => avatars.id),
},
(t) => ({
pk: primaryKey({ columns: [t.avatarId, t.friendId] }),
}),
);

export const avatarsToFriendsRelations = relations(avatarsToFriends, ({ one }) => ({
friend: one(avatars, {
fields: [avatarsToFriends.friendId],
references: [avatars.id],
}),
avatar: one(avatars, {
fields: [avatarsToFriends.avatarId],
references: [avatars.id]
}),
}));
The problem is that I want the relation to be displayed under “Friends” for both avatars. The current situation is that, depending on the relation, the friends are displayed in two different relation fields. Does anyone here have any ideas?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server