Many to many relation in one request

I have custom types

gallery_page
gallery_category - this has relation to gallery_page

How i can get all gallery_category which gallery_page (which related on gallery_category). I want to create one request but i think it is impossible. my code

const allCategories = await client.getAllByType('gallery_category')
const data = allCategories.map(async (category) => {
      const categoryGalleries = (await client.get<GalleryPageDocument>({
        pageSize: 100,
        predicates: [
          predicate.at('my.gallery_page.gallery_category', category.id)
        ]
      })).results;

return {category, categoryGalleries }

its not good code because i send a lot request on api

Hello @vitali.bakhur,

Welcome to Prismic community, and thanks for reaching out to us.

Yes, it is possible. I ran the code snippet you provided, and it works fine. There are two closing brackets missing from your snippet. By the way, I'm using JS, and I think you are using TS, but it shouldn't be a problem.

So it should look like this,

  const data = allCategories.map(async (category) => {
    const categoryGalleries = (
      await client.get({
        pageSize: 100,
        predicates: [
          predicate.at("my.gallery_page.gallery_category", category.id),
        ],
      })
    ).results;

    return { category, categoryGalleries };
  });

And the way I like to use predicates is as follows:

  const categoryGalleries = await client.get({
    predicates: [
      predicate.at("document.type", "gallery_page"),
      predicate.at("my.gallery_page.gallery_category", category.id),
    ],
  });

Get the document type first, then filter it.

I hope this helps. :slight_smile:

Cheers,
Racheal.

1 Like