如何在 Drizzle ORM 中声明自引用外键

问题描述 投票:0回答:1

在 Typescript 项目中,使用 Drizzle 和 postgres-node 声明一个表,如下所示:

const contractsTable = pgTable("contracts", {
    id: serial("id").primaryKey(),
    underlyingId: integer("underlying_id").references(() => contractsTable.id),
    ...
})

导致以下 Typescript 错误:

'contractsTable' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

维护单独的类型是不切实际的,因为模式很大并且会不时发生变化。

有没有办法让 Typescript 推断出正确的类型?我未能通过别名或转换 PgIntegerBuilderInitial 类型来做到这一点。

我们还定义了一个关系如下:

export const contractsRelations = relations(
    contractsTable,
    ({ one, many }) => ({
        underlying: one(contractsTable, {
            fields: [contractsTable.underlyingId],
            references: [contractsTable.id],
        }),
        ...
    })
);

但我确实需要数据库级别的约束。有什么想法吗?

typescript postgresql orm node-postgres drizzle
1个回答
0
投票

根据【BUG】:自引用外键破坏关系查询类型#1607,可以这样解决:

export const contractsTable = pgTable("contracts", {
    id: serial("id").primaryKey(),
    underlyingId: integer("underlying_id").references((): AnyPgColumn => contractsTable.id),
})

export const contractsRelations = relations(
    contractsTable,
    ({ one, many }) => ({
        underlying: one(contractsTable, {
            fields: [contractsTable.underlyingId],
            references: [contractsTable.id],
        }),
    })
);
© www.soinside.com 2019 - 2024. All rights reserved.