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字段匹配父分类的idsubCategories:多端关联,通过当前分类的id匹配所有parentCategoryId等于当前ID的子分类- 统一的
relationName让Drizzle明确这是一组双向自引用关联
内容的提问来源于stack exchange,提问作者Phaedrus
相关产品推荐
相关产品推荐

