细雨:db.query 抛出未定义不是一个对象(评估“relation.referencedTable”)

问题描述 投票:0回答:1

所以我有这些模式称为

products.ts
category.ts
,这些文件之间的关系是一对多

产品.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

类别.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

但是当我尝试查询 findMany 时,它会抛出错误

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

你能帮我解决这个问题吗?

预期的输出是该查询中显示的数据,如下所示

type CategoryWithProducts = {
    id: string;
    name: string | null;
    createdAt: Date;
    updatedAt: Date | null;
    products: Products[];
}
typescript postgresql relationship drizzle drizzle-orm
1个回答
0
投票

理想情况下,Drizzle 会使此错误消息更加具体,但我的理解是,这意味着 Drizzle 不知道

categories
products
之间的任何关系。

一个常见的设置错误是仅在 Drizzle 客户端中导入架构。

例如,如果您当前有:

const db = drizzle(client, {
    schema: {
       products,
       categories,
    },
});

那么您的关系不会导入到 Drizzle 中,您将收到所看到的错误消息。

相反,您需要:

const db = drizzle(client, {
    schema: {
       products,
       productsRelations,
       categories,
       categoriesRelations,
    },
});

我不确定这是您的问题,但我希望这对您或其他人有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.