I’m working on a controller that copies data from one collection, let’s call it CollectionA, and pastes it into another collection, CollectionB. In CollectionA, there’s a field called key, which uniquely identifies each entry. CollectionB has a one-way relationship field that should be mapped to the key field from CollectionA. While copying the data from CollectionA to CollectionB, I’m successfully filling in most of the values, but I’m having trouble correctly mapping the relationship field in CollectionB with the corresponding key from CollectionA.
Here is the code:
const { createCoreController } = require('@strapi/strapi').factories;
const { errors } = require("@strapi/utils");
const { ApplicationError } = errors;
module.exports = createCoreController(
"api::global-var-agency-map.global-var-agency-map",
({ strapi }) => ({
async initSetup(ctx) {
// const newTransaction = strapi.db.connection.transaction();
return await strapi.db.transaction(
async ({ trx, rollback, commit, onCommit, onRollback }) => {
try {
const request = ctx.request.body?.data || {};
if (
!request.agencyId ||
!["global-var-osmos-template"]?.includes(request.templateName)
) {
return ctx.badRequest(
"Incorrect Payload. agencyId & templateName are required."
);
}
const templateData = await strapi.entityService.findMany(
`api::${request.templateName}.${request.templateName}`,
{
populate: "*",
filters: { publishedAt: { $notNull: true } },
}
);
const dataToInsert = templateData?.map((data) => {
return {
marketplaceClientId: request.clientId,
agencyId: request.agencyId,
publishedAt: Date.now(),
value: data.defaultValue,
visibility: data.defaultVisibility,
globalConfigRelation: data.key,
};
});
await strapi.db
.query("api::global-var-agency-map.global-var-agency-map")
.createMany({
data: dataToInsert,
});
commit();
return {
status: "OK",
};
} catch (e) {
console.error(e);
rollback();
throw new ApplicationError(e.message);
}
}
);
},
})
);
Here I am trying to map globalConfigRelation with the data.key but it is not happening