Search code examples
javascriptlaravelormprisma

Using prisma how to get the newly created records id(pk)?


After creating a new record using Prisma ORM how do I get the ID of newly created record to do some other operation using that ID?

For example in Laravel Eloquent I could create a product using insertGetId

$product_id = Product::insertGetId([
  'cat_id' => $request->cat_id,
  'name' => $request->name,
  'price' => $request->price,
  'created_at' => Carbon::now()
]);

And then use that Id to do some other related task like save products images in another table(using $product_id):

ProductMultiImage::insert([
  'product_id' => $product_id,
  'photo_name' => $upload_path,
  'created_at' => Carbon::now(),
]);

So when creating some record using Prisma's createMany method how can I get the new records id?

export async function action({ request }) {

  const inputData = await request.formData();

  const parsedData = JSON.parse(inputData.get("data"));

  const formattedData = parsedData.map(data => ({
    discountTypeId: 1,
    discountValue: 121,
    productId: data.productId,
  }));

  await db.discountedProducts.create({
    data: [...formattedData],
  });

  // Want to do something else using the newly created discountedProducts id 

  return redirect("/app");
}

How can I achieve similar functionality in Prisma ORM?


Solution

  • In Prisma when you're creating a record using the create method it returns the newly created data along with all it's fields as a object. So after creating it you can access the newly created records id from there.

    Here is an example:

    const bundle = await db.bundles.create({
      data: {
        bundleTypeId: bundleType,
        discountTypeId: discountType,
        discountValue: discountVal,
      },
    });
    
    
    const bundleId = bundle.id;