How to implement an 'or' operator in supabase

322 Views Asked by At

How are you? I'm having trouble implementing the or operator in supabase.

I need to create a 'for you' tab, so I'm trying to filter the posts depending on the tags and people the user follows.

When I implement the in and contains operators separately, it works fine. But when I implement the or operator, it fails. Also, I've tried doing .or(`tags.contains.${tags || []}, created_by.id.in.${following || []}`) also

  const { data, error } = await supabase
    .from("post")
    .select(
      "title, description, likes, cover_image, views, slug, created_at, published, id, tags, created_by!inner( name, profile_image, default_profile_img_color, id, description, username, cafecito )"
    )
    .eq("published", true)
    .contains("tags", tags || [])
    .order("created_at", { ascending: false })
    .limit(limit);
  const { data, error } = await supabase
    .from("post")
    .select(
      "title, description, likes, cover_image, views, slug, created_at, published, id, tags, created_by!inner( name, profile_image, default_profile_img_color, id, description, username, cafecito )"
    )
    .eq("published", true)
    .in('created_by.id', following || [])
    .order("created_at", { ascending: false })
    .limit(limit);

  const { data, error } = await supabase
    .from("post")
    .select(
      "title, description, likes, cover_image, views, slug, created_at, published, id, tags, created_by!inner( name, profile_image, default_profile_img_color, id, description, username, cafecito )"
    )
    .eq("published", true)
    .or(`tags.cn.${tags || []}, created_by.id.in.${following || []}`)
    .order("created_at", { ascending: false })
    .limit(limit);
1

There are 1 best solutions below

0
On

or filter expects the raw postgREST syntax, which makes it a bit unique to work with. For contains, the array has to be wrapped in {}, and for in, the array has to be wrapped in ().

Also, contains filter is cs, and not cn.

So you would want something like this at the end:

.or(`tags.cs.{"tag1", "tag2"}, created_by.id.in.("id1", "id2")`)

You can read more about it on the official docs here https://supabase.com/docs/reference/javascript/or?example=use-or-on-referenced-tables