You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drizzle同表一对多关联查询报错,求正确实现语法

解决Drizzle ORM自关联文章表查询子文章的报错问题

你的报错源于自关联关系定义时未明确字段映射规则,Drizzle无法自动推断父文章与子文章的关联逻辑。以下是具体修正方案:

修正Schema中的关系定义

替换你当前的关系代码,明确指定父表与子表的关联字段:

export const articles = pgTable('articles', {
    id: uuid('id').defaultRandom().primaryKey(),
    title: varchar('title', { length: 600 }).notNull(),
    description: varchar('description'),    
    parentArticleId: uuid('parent_article_id').references(() => articles.id)
});

export const articlesRelations = relations(articles, ({ many }) => ({
    childarticles: many(articles, {
        relationName: 'parent_child_articles', // 给自关联设置唯一名称,避免冲突
        fields: [articles.id], // 父文章的关联字段
        references: [articles.parentArticleId] // 子文章中关联父文章的字段
    })
}));

修正后的查询代码

现在可以正常关联查询子文章:

db.query.articles.findMany({
    where: and(...filter),
    with: {
        childarticles: true
    }
});

关键说明

  • 自关联必须明确fields(父表关联字段)和references(子表对应关联字段),否则Drizzle无法确定关联条件
  • relationName用于区分自关联的不同方向,避免命名冲突

内容的提问来源于stack exchange,提问作者Erik Hauters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:02:49