Search code examples
filterstrapi

Get total count with pagintion in strapi v4


I am implementing pagination in strapi v4. I am using below query.

const favorites = await strapi.db.query("api::gem.gem").findMany({
   where: { id: { $in: user.favorites.map((f) => f.id) } },
   offset: page > 1 ? (page - 1) * pageSize : 0,
   limit: pageSize,
   orderBy: { [sort]: order ? order : "asc" },
});

I want to get the count of all records which satisfies the condition.

I have tried passing withCount:true and count:true but nothing worked.

Any help will be much appreciated!


Solution

  • There is a function called findWithCount() which does what you need

    const [entries, count] = await strapi.db.query('api::blog.article').findWithCount({
      select: ['title', 'description'],
      where: { title: 'Hello World' },
      orderBy: { title: 'DESC' },
      populate: { category: true },
    });
    

    source: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/query-engine/single-operations.html#findwithcount