1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Supabase】条件によってwhere句を動的に変更したい

Posted at

はじめに

Supabaseでデータを取得する際に、条件によってWhere句のパラメータを変えたいと考えていました。
意外とシンプルな方法で解決できたため、調べたことをまとめました。

問題

パラメータの値によってWhere句を変更したい。

export const getDataByAlcohols: (
  props: AdditivesSearch
) => Promise<Partial<Alcohols>[]> = async (props) => {
  const { sake_name, maker } = props;
  const { data, error } = await supabase
    .from("alcohols")
    .select("* , alcohol_genres(genre_name) , manufacturers(manufacturer_name)")
    .like(`sake_name`, `%${sake_name}%`)
    .eq(`manufacturer_id`, `${maker}`); //ここでmakerが空の時はこの条件をつけたくない
};

解決

queryを変数で格納し、if文で条件を追加する

export const getDataByAlcohols: (
  props: AdditivesSearch
) => Promise<Partial<Alcohols>[]> = async (props) => {
  const { sake_name, maker } = props;
-  const { data, error } = await supabase
+  let query = supabase
    .from("alcohols")
    .select("* , alcohol_genres(genre_name) , manufacturers(manufacturer_name)")
    .like(`sake_name`, `%${sake_name}%`);

+  if (maker) {
+    query = query.eq(`manufacturer_id`, `${maker}`);
+  }
  
+  const { data, error } = await query;
};

おわりに

条件によってWhere句を変えたい、and検索やor検索だけでは実現できないな、難しいなと考えていました。意外とシンプルな方法で解決できました。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?