Recursive category search

default discord avatar
hellboy12412412 months ago

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
    ysione11 months ago

    Hi, sounds like max depth should help with that
  • default discord avatar
    hellboy12412411 months ago

    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
    11 months ago

    You’d need to use the


    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


    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


Chat on Discord



Can't find what you're looking for?

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