Self referencing

I have schema:
export const categories = pgTable('categories',{
id: integer('id').primaryKey(),
name: varchar('name',{length: 255}),
parent: integer('parent').references((): AnyPgColumn => categories.id)
});

export const categoriesOneRelations = relations(categories, ({ one }) => ({
parent: one(categories, { fields: [categories.parent], references: [categories.id] }),
}));

export const categoriesManyRelations2 = relations(categories, ({ many }) => ({
children: many(categories),
}));
export const categories = pgTable('categories',{
id: integer('id').primaryKey(),
name: varchar('name',{length: 255}),
parent: integer('parent').references((): AnyPgColumn => categories.id)
});

export const categoriesOneRelations = relations(categories, ({ one }) => ({
parent: one(categories, { fields: [categories.parent], references: [categories.id] }),
}));

export const categoriesManyRelations2 = relations(categories, ({ many }) => ({
children: many(categories),
}));
Code:
const categories = await db.query.categories.findMany({
with: {
children: true
},
});

console.log('categories:', JSON.stringify(categories, null, 2));
const categories = await db.query.categories.findMany({
with: {
children: true
},
});

console.log('categories:', JSON.stringify(categories, null, 2));
after execute then throw exeception
drizzle-orm/alias-72a4082c.cjs:3541
: new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
^

Error: There are multiple relations between "categories" and "categories". Please specify relation name
drizzle-orm/alias-72a4082c.cjs:3541
: new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
^

Error: There are multiple relations between "categories" and "categories". Please specify relation name
Please help me!
2 Replies
MAST
MAST2y ago
I'm not sure but I think this should work:
export const categoriesOneRelations = relations(categories, ({ one }) => ({
parent: one(categories, { fields: [categories.parent], references: [categories.id], relationName: 'parent', }),
children: many(categories, relationName: 'children'),
}));
export const categoriesOneRelations = relations(categories, ({ one }) => ({
parent: one(categories, { fields: [categories.parent], references: [categories.id], relationName: 'parent', }),
children: many(categories, relationName: 'children'),
}));
Liltripple_reid
Liltripple_reid15mo ago
what if I just need the children relation? it throws errors
Want results from more Discord servers?
Add your server