Insert One to Many
How can I insert relations as well at create the parent?
My schema:
I want to add products to the insert for creating the new journey. Currently using a transaction but not sure what the code needs to be for linking products to the journey?
import { Customer } from "@/types/customer";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { db } from "@/lib/db";
import { journeys } from "@/lib/db/schema";
import { v4 as uuidv4 } from "uuid";
export async function POST(req: Request) {
const body = (await req.json()) as Customer;
// Body has product refs...
const journeyRef = uuidv4();
await db.transaction(async (tx) => {
await tx.insert(journeys).values({ ...body, journeyRef });
// Then need to link products to that journey...
});
cookies().set({
name: "journeyRef",
value: journeyRef,
httpOnly: true,
path: "/",
});
return NextResponse.json({});
}import { Customer } from "@/types/customer";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { db } from "@/lib/db";
import { journeys } from "@/lib/db/schema";
import { v4 as uuidv4 } from "uuid";
export async function POST(req: Request) {
const body = (await req.json()) as Customer;
// Body has product refs...
const journeyRef = uuidv4();
await db.transaction(async (tx) => {
await tx.insert(journeys).values({ ...body, journeyRef });
// Then need to link products to that journey...
});
cookies().set({
name: "journeyRef",
value: journeyRef,
httpOnly: true,
path: "/",
});
return NextResponse.json({});
}My schema:
import { mysqlTable, serial, text } from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm";
export const journeys = mysqlTable("journey", {
id: serial("id").primaryKey(),
journeyRef: text("journeyRef"),
customer_firstName: text("customer_firstName"),
customer_lastName: text("customer_lastName"),
customer_emailAddress: text("customer_emailAddress"),
type: text("type"),
});
export const products = mysqlTable("product", {
id: serial("id").primaryKey(),
name: text("name"),
});
export const journeysRelations = relations(journeys, ({ many }) => ({
products: many(products),
}));import { mysqlTable, serial, text } from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm";
export const journeys = mysqlTable("journey", {
id: serial("id").primaryKey(),
journeyRef: text("journeyRef"),
customer_firstName: text("customer_firstName"),
customer_lastName: text("customer_lastName"),
customer_emailAddress: text("customer_emailAddress"),
type: text("type"),
});
export const products = mysqlTable("product", {
id: serial("id").primaryKey(),
name: text("name"),
});
export const journeysRelations = relations(journeys, ({ many }) => ({
products: many(products),
}));I want to add products to the insert for creating the new journey. Currently using a transaction but not sure what the code needs to be for linking products to the journey?