Open2
Supabase で行を Count するクエリを作成する
Supabaseで、以下のように行数をカウントするクエリを JS で発行したい。
select count(*) from `post_likes` where `post_id` = 2;
該当する行を data に格納する方法
const {data, error, count} = await supabase.from('post_likes')
.select('*', {count: 'exact'})
.match({ post_id: 2})
console.log(data, error, count);
実行結果は以下
[
{
post_id: 2,
user_id: 'uuid-uuid-uuid-uuid',
read: true
}
] null 1
該当する行を data に格納しない方法
const {data, error, count} = await supabase.from('post_likes')
.select('*', {count: 'exact', head: true})
.match({ post_id: 2})
console.log(data, error, count);
実行結果は以下。
null null 1
count
という返り値に格納されている。が、なかなかドキュメントで見つけにくい。
参考
JS で join したテーブルのカウント方法は以下の通り。
const { data, error } = await supabase
.from('users')
.select(`
name,
tweets (
count
)
`)
以下のように取得できる。
tweets [{ count: 0 }]