How can one make bulk operations on relations?

Hey, I’ve found a solution. (Strapi v4.2.0)

Since relations are store in separate tables, you need to handle them separately, here is my problem and how I solved it:

I wanted to save a list of coupon codes for a specific product, so the input here is couponCodes as an array of strings and the productId as a string.

const batchSize = 10000
let batch = couponCodes.splice(0, batchSize)

while (batch.length > 0) {
  await strapi.db.query('api::coupon-code.coupon-code').createMany({ data: batch.map(code => ({ code })) })

  const codes = await strapi.db.query('api::coupon-code.coupon-code').findMany({ where: { code: { $in: batch } } })

  const links = codes.map(code => ({ coupon_code_id: code.id, product_id: productId }))

  await strapi.db.connection.insert(links).into('coupon_codes_product_links')

  batch = couponCodes.splice(0, batchSize)
}

So I had to look up the name and fields of the _links table that was automatically created for the relation between Coupon Codes and Product.

1 Like