Insert a record, then another record with the id of the first one in the same transaction
Hello,
I have some tables
This is the schema:
I'm trying to construct a create function but I'm not sure how to get the orderId first to assign it to all the
Is this the correct approach?
Thanks!
I have some tables
ordersorders and order_productsorder_productsThis is the schema:
orders: defineTable({
organizationId: v.id('organizations'),
customerId: v.id('customers'),
salesChannelId: v.id('sales_channels'),
status: v.string(),
folio_number: v.number(),
}),
order_products: defineTable({
orderId: v.id('orders'),
productId: v.id('products'),
quantity: v.number(),
price: v.number(),
discount: v.number(),
taxes: v.array(v.id('taxes')),
})orders: defineTable({
organizationId: v.id('organizations'),
customerId: v.id('customers'),
salesChannelId: v.id('sales_channels'),
status: v.string(),
folio_number: v.number(),
}),
order_products: defineTable({
orderId: v.id('orders'),
productId: v.id('products'),
quantity: v.number(),
price: v.number(),
discount: v.number(),
taxes: v.array(v.id('taxes')),
})I'm trying to construct a create function but I'm not sure how to get the orderId first to assign it to all the
order_productsorder_productsIs this the correct approach?
export const createOrder = mutation({
args: {
organizationId: v.id('organizations'),
salesChannelId: v.id('sales_channels'),
customerId: v.id('customers'),
products: v.array(
v.object({
productId: v.id('products'),
quantity: v.number(),
price: v.number(),
discount: v.number(),
taxes: v.array(v.id('taxes')),
})
),
},
handler: async (ctx, args) => {
const { organizationId, salesChannelId, customerId } = args
const orderId = await ctx.db.insert('orders', {
organizationId,
salesChannelId,
customerId,
folio_number: 1,
status: 'pending',
})
args.products.forEach(async (product) => {
await ctx.db.insert('order_products', {
orderId,
productId: product.productId,
quantity: product.quantity,
price: product.price,
discount: product.discount,
taxes: product.taxes || [],
})
})
},
})export const createOrder = mutation({
args: {
organizationId: v.id('organizations'),
salesChannelId: v.id('sales_channels'),
customerId: v.id('customers'),
products: v.array(
v.object({
productId: v.id('products'),
quantity: v.number(),
price: v.number(),
discount: v.number(),
taxes: v.array(v.id('taxes')),
})
),
},
handler: async (ctx, args) => {
const { organizationId, salesChannelId, customerId } = args
const orderId = await ctx.db.insert('orders', {
organizationId,
salesChannelId,
customerId,
folio_number: 1,
status: 'pending',
})
args.products.forEach(async (product) => {
await ctx.db.insert('order_products', {
orderId,
productId: product.productId,
quantity: product.quantity,
price: product.price,
discount: product.discount,
taxes: product.taxes || [],
})
})
},
})Thanks!
