How can one make bulk operations on relations?

System Information
  • Strapi Version: 4.1.10
  • Operating System: Linux
  • Database: SQLite
  • Node Version: 14.16.0
  • NPM Version: 6.14.11
  • Yarn Version: 1.22.5

On strapi v3.6 query builder could be used to make such operations. In strapi v4 bulk operations are supported but as it is on documentation: To avoid performance issues, bulk operations are not allowed on relations.

How to make a bulk operation on strapi v4 supporting relations?

As an example (this does’nt work):

await strapi.db.query("api::account.account").createMany({
  data: [{ ...account, foreignKey }, ...manyOthers],
1 Like

I am also looking for creating bulk entries using createMany function on relations.
Have you found the solution to this?

Any help would be appreciated.

Hello, I’m having the same problem, It’s not saving the relation id and I think creating entries one by one is a very suboptimal solution, heavy and slow.

is anyone able to solve how to save foreign key in bulk operation ?

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('').createMany({ data: => ({ code })) })

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

  const links = => ({ coupon_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