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

Drizzle ORM自引用分类表关联报错:无法推断subCategories关联

解决Drizzle ORM自引用分类关联的推断错误

错误原因

自引用关联的多端(subCategories)配置缺失了关联字段的映射规则,导致Drizzle无法自动推断关联关系,抛出There is not enough information to infer relation错误。

修复方案

给subCategories的many关联补充字段映射配置,并确保双向关联的relationName保持一致:

export const categories = pgTable("categories", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  userId: text("user_id").notNull(),
  parentCategoryId: text("parent_category_id").references(
    () => categories.id
  ),
});

export const categoriesRelations = relations(
  categories,
  ({ many, one }) => ({
    transactions: many(transactions),
    savedCategories: many(savedCategories),
    subCategories: many(categories, {
      relationName: "parent_category",
      fields: [categories.id], // 当前分类的ID作为关联匹配字段
      references: [categories.parentCategoryId], // 关联子分类的parentCategoryId字段
    }),
    parentCategory: one(categories, {
      fields: [categories.parentCategoryId],
      references: [categories.id],
      relationName: "parent_category",
    }),
  })
);

配置说明

  • parentCategory:单端关联,通过当前分类的parentCategoryId字段匹配父分类的id
  • subCategories:多端关联,通过当前分类的id匹配所有parentCategoryId等于当前ID的子分类
  • 统一的relationName让Drizzle明确这是一组双向自引用关联

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:27:15