javascriptone-to-manydrizzle

Drizzle one to many relation to the same table


I have a table of articles, an article can have a parent article. Meaning that a parent article references many child articles. I can't find a way to query for all articles and join their child articles.

Thanks for helping me out.

This is in my schema.ts file:

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 childArticlesRelation = relations(articles, ({ many }) => ({
    childarticles: many(articles, { relationName: 'childarticles' })
}));

And now I want to query for articles and join their child articles:

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

That gives me: There is not enough information to infer relation "articles.childarticles" Which I understand, but I can't find anything in the docs that gives me the correct syntax.


Solution

  • I solved it by adding the proper relationName:

    export const articleChildrenRelation = relations(articles, ({ many }) => ({
        childarticles: many(articles, { relationName: 'childarticles' })
    }));
    
    
    export const childArticleRelation = relations(articles, ({ one }) => ({
        parentArticle: one(articles, {
           fields: [articles.parentArticleId],
           references: [articles.id],
           relationName: 'childarticles'
        })
    }));