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
The relational query API requires you to define the relation with the
relation
functionOk 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?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
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