Tharaka
Tharaka
DTDrizzle Team
Created by Tharaka on 5/1/2023 in #help
Inserting records into related tables
I have a few of tables that are related. I just need to know if there's a better approach when inserting records into these. I'm using PlanetScale so no FK constraints. Here's my approach.
export const product = mysqlTable('product', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 256 }),
description: varchar('description', { length: 256 }),
});

export const productVariant = mysqlTable('product_variant', {
id: serial('id').primaryKey(),
productId: int('product_id'),
name: varchar('name', { length: 256 }),
description: varchar('description', { length: 256 }),
});

export const variantAsset = mysqlTable('variant_asset', {
id: serial('id').primaryKey(),
variantId: int('variant_id'),
assetName: varchar('asset_name', { length: 256 })
});
export const product = mysqlTable('product', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 256 }),
description: varchar('description', { length: 256 }),
});

export const productVariant = mysqlTable('product_variant', {
id: serial('id').primaryKey(),
productId: int('product_id'),
name: varchar('name', { length: 256 }),
description: varchar('description', { length: 256 }),
});

export const variantAsset = mysqlTable('variant_asset', {
id: serial('id').primaryKey(),
variantId: int('variant_id'),
assetName: varchar('asset_name', { length: 256 })
});
Insert statements
const newProduct = await db.insert(product).values({
name: 'Product name',
description: 'Product description',
});

const newProductVariant = await db.insert(productVariant).values({
** productId: newProduct.insertId**,
name: 'Variant name',
description: 'Variant description',
});

const newVariantAsset = await db.insert(variantAsset).values({
** variantId: newProductVariant.insertId,**
assetName: 'Asset Name',
});
const newProduct = await db.insert(product).values({
name: 'Product name',
description: 'Product description',
});

const newProductVariant = await db.insert(productVariant).values({
** productId: newProduct.insertId**,
name: 'Variant name',
description: 'Variant description',
});

const newVariantAsset = await db.insert(variantAsset).values({
** variantId: newProductVariant.insertId,**
assetName: 'Asset Name',
});
I just need to know if there's a better approach to this? Instead of writing three, can we batch them?
9 replies