How to make one object have 2 different relationships with another object.

I have 2 tables Product and Media. The product has a thumbnail and also images of the product. The thumbnail is one media and images are many media.

So in short I have to have one-to-one relation between Product.thumbnail and Media, and a one-to-many relation between Product.images and Media.

My code follows the docs about relations but it does not work (my guess because of circular references).

export const Product = pgTable("product", {
  id: uuid("id").primaryKey().defaultRandom(),
  title: varchar("title", { length: 128 }).notNull(),
  description: varchar("description", { length: 1024 }),
  // the product "owns" the Media in thumbnail
  thumbnailId: uuid("thumbnail_id").references(() => Media.id),
})

export const Media = pgTable("media", {
  id: uuid("id").primaryKey().defaultRandom(),
  url: varchar("url", { length: 512 }).notNull(),
  // needs to reference productId to correctly implement a one-to-many relation
  productId: uuid("product_id").references(() => Product.id),
})

export const ProductRelations = relations(Product, ({ one, many }) => ({
  thumbnail: one(Media, {
    fields: [Product.thumbnailId],
    references: [Media.id],
  }),
  images: many(Media),
}))

export const MediaRelations = relations(Media, ({ one, many }) => ({
  productThumbnail: one(Product),
  productImages: one(Product, {
    fields: [Media.productId],
    references: [Product.id],
  }),
}))


These lines cause a TS error:

thumbnailId: uuid("thumbnail_id").references(() => Media.id),
productId: uuid("product_id").references(() => Product.id),


Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.


How do I correctly implement 2 different relations between 2 tables?
Was this page helpful?