Help needed to achieve the intersection of categories between fetched blogs in Sanity.io

4 replies
Last updated: Jul 14, 2023
Hi,
I have this blog page, that displays links to other similar blogs. The similarity is based on category, where every blog can have multiple string categories. So basically, in a blog that has ["Design", "Research"] categories, I need to display links to blogs with either "Design" or "Research" category. Note that they can have other categories as well.
I have this small query that works only with 1 category. Can somebody help me achieve the intersection of categories between fetched blogs?


`*[_type == 'blog' && $category in categories] {
      _id,
      _updatedAt,
      categories,
      description,
      title,
      timeToRead,
      publishedAt,
    }`,
    {
      category,
    }
Instead of
_type == 'blog' && $category in categories
I need something like
_type == 'blog' && ($category *has any in* categories)
where
$category
is also an array.
Thanks.
Jul 12, 2023, 10:51 AM
Note that
$category match categories
does not work as it expects all left side values to be included in right side values.
Jul 12, 2023, 11:01 AM
I just need
any
Jul 12, 2023, 11:01 AM
Hi
user R
. Can you please give the examples at the end of the Filters list a try (the ones with
[@ in "action", "thriller"]
)? I believe that syntax is what you’re after.
Jul 12, 2023, 2:41 PM
Did not work for me.
If somebody is still searching for a solution, this is what I did:


export const getBlogsBasedOnCategory = async (
  curentBlogCategories: BlogCategory[],
  currentBlogId: string,
) => {
  const queryCondition = curentBlogCategories.reduce(
    (acc: string, cv: BlogCategory) => {
      const addition = !acc
        ? `"${cv}" in categories`
        : ` || "${cv}" in categories`;
      return acc + addition;
    },
    '',
  );

  return SanityClient.fetch(
    `*[_type == 'blog' && _id != $id && (${queryCondition})][0..2] {
    _id,
    _updatedAt,
    slug,
    categories,
    description,
    title,
    timeToRead,
    publishedAt,
    image
  }`,
    {
      id: currentBlogId,
    },
  );
};
Jul 14, 2023, 9:02 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?