Lifecycle and components inside collections type

@WaiYan_Kyaw @error_n73

You have to use the component/relation id to query it in it’s specific table.

  • Step 1: Query the component data in your collection’s table:
  • Step 2: Query the current component data in the component’s table, using the id that you have in data itself
  • Step 3: Validate the data as you wish

Example:

lifecycles.js

// get your component data from your collection’s table
const allTerms = await someFile.fetchAllTerms();

// get currentRecord terms from the component's table
const currTerms = await someFile.fetchCurrentTerms(data.terms);

// Validate the data as you wish

someFile.js

// Let's say that the field's name which represents the component  is called: "terms"

// fetch all terms data that are already registered in your collection
async function fetchAllTerms() {
  const records = await strapi.entityService.findMany("your-collection-table-path", {
    populate: ["terms"], // "populate" here is necessary to get the relation data
  });

  const terms = records.map((item) => item.terms);

  return terms;
}

// fetch the lifecycle current component data
// Note: the table that we use here is the components table
async function fetchCurrentTerms(terms) {
  const currTerms = [];
  for (const term of terms) {
    const currTerm = await strapi.entityService.findOne(
      "components.your-component-name",
      term.id, // You use the id from your component that you see inside of data in a lifecycle hook
      {
        fields: ["someFieldName"],
      }
    );
    currTerms.push(currTerm);
  }
  return currTerms;
}

module.exports = {
  fetchAllTerms,
  fetchCurrentTerms,
};

Hope this helps some developers who went through this issue