drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[FEATURE]: Allow for hardcoded values in relations

Open Ziothh opened this issue 1 year ago • 0 comments

Describe what you want

I want to add a media relation to my invoices table. The media table can point to any table via the media.attachableType column.

In this case the attachable type is "invoice" which I want to hard code into the relation definition. The media.attachableId column references the PK of the invoices table.

Is this supported in any way atm?

SELECT
    *
FROM
    "invoices"
    INNER JOIN "media" ON (
        "media"."attachable_type" = 'invoice' -- Hard coded value
        AND "media"."attachable_id" = "invoices"."id"
    )
export const media = pgTable(
    'media',
    {
        id: serial('id').primaryKey().notNull(),
        attachableType: varchar('attachable_type', { length: 255 }).$type<
            mediaSDK.MediaType | (string & {})
        >(),
        attachableId: integer('attachable_id'),

        // Snip...

        createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).defaultNow(),
        updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' }).defaultNow(),
    },
    (table) => ({
        mediaAttachabletypeAttachableidPathUnique: unique(
            'media_attachabletype_attachableid_path_unique',
        ).on(table.attachableType, table.attachableId, table.path),
    }),
)
export const invoices = pgTable('invoices', {
    id: serial('id').primaryKey().notNull(),
   
    // Snip...

    createdAt: timestamp('created_at', { withTimezone: true, mode: 'date' }).defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date' }).defaultNow(),
})
export const invoiceRelations = relations(invoices, ({ one }) => ({
    deal: one(deals, {
        references: [deals.id],
        fields: [invoices.dealID],
    }),
    tenant: one(tenants, {
        references: [tenants.id],
        fields: [invoices.tenantID],
    }),
    media: one(media, {
        references: [media.attachableId, media.attachableType],
        fields: [invoices.id, 'invoice'], // I want to hard code this value
    }),
}))

Ziothh avatar May 07 '24 06:05 Ziothh