Recursive category search

default discord avatar
hellboy124124last year
5

Hey, like the title says, I am wondering if there is a native way with payload CMS to execute a recursive category search, for example my schema:


Products - id, slug, name, category (relationship), ...


Categories - id, slug, name, parent (relationship to self), ...



Now, what I basically want to do, when I'm querying /api/products, I'm sending { where: { category: { equals: 'some-category-id' } } } to the API, I would want it to be recursively including all the child categories for that category? Is that possible or are there any other hack-y ways to achieve this?

  • default discord avatar
    ysionelast year

    Hi, sounds like max depth should help with that


    https://payloadcms.com/docs/production/preventing-abuse#max-depth
  • default discord avatar
    hellboy124124last year

    Hey, in what sense would that help? Right now, in a rather hack-y way I added a new endpoint to the categories called /hierarchy, which I then get on the frontend, and once I am in a category, I just send that category + all of it's children with it, but it's not really optimal, so I'm curous to how I would be able to optimise that a bit

  • discord user avatar
    jacobsfletch
    last year

    You’d need to use the

    in

    operator for your query and send an array of category ids like this:

    { category: { in: [123, 456] }}


    To easily get a list of ids within your category tree, you could install the official nested docs plugin and enable it on your category collection



    This will generate a

    breadcrumbs

    array on each category, this will enable you to query on the top level breadcrumb to get all categories within that hierarchy

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.