drizzle: db.query throwing undefined is not an object (evaluating 'relation.referencedTable')

60 views Asked by At

so i have these schema called products.ts and category.ts, the relationship between those files is one-to-many.

product.ts

import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
import { categories } from "./category";
import { relations } from "drizzle-orm";

export const products = pgTable("products", {
    id: uuid("id").primaryKey().defaultRandom(),
    name: varchar("name", { length: 255 }),
    categoryId: uuid("category_id").notNull().references(() => categories.id),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").defaultNow(),
    deletedAt: timestamp("deleted_at"),
})

export const productsRelations = relations(products, ({ one }) => ({
    category: one(categories,{
        fields: [products.categoryId],
        references: [categories.id],
    })
}))

export type Product = typeof products.$inferSelect
export type NewProduct = typeof products.$inferInsert

category.ts

import { relations } from "drizzle-orm";
import { pgTable, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
import { products } from "./product";

export const categories = pgTable("categories", {
    id: uuid("id").primaryKey().defaultRandom(),
    name: varchar("name", { length: 255 }),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").defaultNow(),
}, (category) => {
    return {
        nameIndex: uniqueIndex("name_index").on(category.name),
    }
})

export const categoriesRelations = relations(categories, ({ many }) => ({
    products: many(products)
}))

export type Category = typeof categories.$inferSelect
export type NewCategory = typeof categories.$inferInsert

But when i try to do query findMany, it throws an error

 await db.query.categories.findMany({
      with: {
        products: true,
      },
    });

Error undefined is not an object (evaluating 'relation.referencedTable')

Can you help me to fix this ?

The expected output is the data from this query are showing and its something like this

type CategoryWithProducts = {
    id: string;
    name: string | null;
    createdAt: Date;
    updatedAt: Date | null;
    products: Products[];
}
0

There are 0 answers