How to create localized entries from code?

I’ve just spent a very decent amount of time scratching my head over this for Strapi v4! The solution I came up with is as follows:

  1. Add the main entity to the db - store the id returned from this query
  2. Add each localized entity to the db - store the ids of each localized entity
  3. Create the relationship between the main entity and the localized entities
  4. Create the reverse relationships between each localized entity and the main entity
const uid = "api::entity.entity";
const { localizations, ...entityWithoutLocalizations } = entity;
        try {
          //  Create main entity without localizations
          const addedEntity = await strapi.entityService.create(uid, {
            data: entityWithoutLocalizations,
          });

          //  Add the id of the inserted main entity to the entity without localizations - we need this later when we set up the reverse relationship
          entityWithoutLocalizations.id = addedEntity.id;

          for (let i = 0; i < localizations.length; i++) {
            //  Create the localization object in the db
            const addedLocalization = await strapi.entityService.create(uid, {
              data: localizations[i],
            });
            //  Add the id of the localization that was just added to the db to the original data
            localizations[i].id = addedLocalization.id;
            //  Create the relationship between the localization and the main entity
            await strapi.query(uid).update({
              where: { id: localizations[i].id },
              data: { localizations: [entityWithoutLocalizations] },
            });
          }

          //  Finally, create the relationship between the main entity and all the localizations
          await strapi
            .query(uid)
            .update({ where: { id: addedEntity.id }, data: { localizations } });
        } catch (e) {
          console.log(e);
        }
1 Like