Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Aggregate function

default discord avatar
eloahsamlast year
3

i created a "AfterRead" in a table called Categories that gets the number of Places with a specific category , the function use to work im not sure why it doesnt now , this is the function



const get = (url, params = {}) => {


const query: any = qs.stringify(params, { addQueryPrefix: true });


console.log(

${url}${query}

);


return fetch(

${url}${query}

);


};


export const queryRelations: any = async (data, route) => {


const request = await get(payload.getAdminURL() + route, {


where: {


// the 'in' operator is used when relations can be more than one


category: { in: data.id },


// to add more query constraints use 'or', 'and' operator objects


},


});



const result: any = await request;


if (result?.docs) {


return result?.totalDocs;


}



if (result.status >= 400) {


return console.error();


}


return 0;


};

  • default discord avatar
    Jarrodlast year

    Sounds like exactly what @jesschow describes in this post about virtual fields:

    https://twitter.com/payloadcms/status/1645759920761962496?s=20

    Give that a watch. In your afterRead hook you can use the local api instead of REST because afterRead hooks only run on the server.



    Here is something I just threw together that I think is what you are looking for:



    {
      name: 'categoryCount',
      type: 'number',
      hooks: {
        beforeChange: [
          ({ siblingData }) => {
            siblingData.categoryCount = undefined;
          },
        ],
        afterRead: [
          async ({ req, originalDoc }) => {
            const docQuery = await req.payload.find({
              collection: 'places',
              where: {
                categories: {
                  in: [originalDoc.id],
                },
              },
            });
    
            return docQuery.totalDocs;
          },
        ],
      },
    }
  • default discord avatar
    eloahsamlast year

    yeah im using that now but created a reusable function for future case if another table needs it



    export const queryRelations: any = async (data) => {
      const experiences = await payload.find({
        collection: "experiences",
        where: {
          // the 'in' operator is used when relations can be more than one
          category: { equals: data.id },
          // to add more query constraints use 'or', 'and' operator objects
        },
        depth: 0,
        limit: 0,
      });
    
      if (experiences?.docs) {
        return experiences?.totalDocs;
      }
    
      return 0;
    };
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team..