Relations include query

For example If I have the following schema: export const sales = mysqlTable("Sales", { id: int("id").autoincrement().notNull(), startingDate: datetime("starting_date", { mode: 'string'}).notNull(), expirationDate: datetime("expiration_date", { mode: 'string'}), bundleId: int("BundleId").references(() => bundles.id, { onDelete: "set null", onUpdate: "cascade" } ), }, (table) => { return { bundleId: index("BundleId").on(table.bundleId), salesId: primaryKey(table.id), } }); export const bundles = mysqlTable("Bundles", { id: int("id").autoincrement().notNull(), amount: float("amount").notNull(), name: varchar("name", { length: 255 }), }, (table) => { return { bundlesId: primaryKey(table.id), } }); I'm trying the following query and it throws me an error: await db.query.sales.findFirst({ where: eq(sales.businessUserId, id), orderBy: desc(sales.id), with: { bundles: true }, }); The error is undefined is not an object (evaluating 'relation.referencedTable'). How can I get a Sale object with it's Bundle complete object instead of only the BundleId? To avoid having to do another query.
5 Replies
Angelelz
Angelelz16mo ago
The relational query API requires you to define the relation with the relation function
rfrancociavaldini
rfrancociavaldiniOP16mo ago
Ok got it. I generated the schema file using drizzle-kit from an existing MySQL database, maybe there's something to check there, should I open an issue?
Angelelz
Angelelz16mo ago
If you used the drizzle-kit introspect feature, I'm pretty sure you need to manually add the relations to the generated schema.ts file
Andrii Sherman
Andrii Sherman16mo ago
Yes, relations() functions is not a part of introspect as long as it has nothing with actual database schema and it's only a rutime helper for drizzle
Want results from more Discord servers?
Add your server