使用过滤器

过滤器允许你只返回符合某些条件的记录。

过滤器可以用于select(), update(), upsert(), 和delete()查询。

如果一个Postgres函数返回一个表的响应,你也可以应用过滤器。

案例1 (应用过滤器)#

1                                                                              
2const { data, error } = await supabase
3  .from('cities')
4  .select('name, country_id')
5  .eq('name', 'The Shire')    // Correct
6
7const { data, error } = await supabase
8  .from('cities')
9  .eq('name', 'The Shire')    // Incorrect
10  .select('name, country_id')

案例2 (链式)#

1                                                                              
2const { data, error } = await supabase
3  .from('cities')
4  .select('name, country_id')
5  .gte('population', 1000)
6  .lt('population', 10000)

案例3 (条件链式)#

1                                                                              
2const filterByName = null
3const filterPopLow = 1000
4const filterPopHigh = 10000
5
6let query = supabase
7  .from('cities')
8  .select('name, country_id')
9
10if (filterByName)  { query = query.eq('name', filterByName) }
11if (filterPopLow)  { query = query.gte('population', filterPopLow) }
12if (filterPopHigh) { query = query.lt('population', filterPopHigh) }
13
14const { data, error } = await query

案例4 (按JSON列中的值过滤)#

1                                                                              
2const { data, error } = await supabase
3  .from('users')
4  .select()
5  .eq('address->postcode', 90210)

案例5 (过滤外键表)#

1                                                                              
2create table
3  countries (id int8 primary key, name text);
4create table
5  cities (
6    id int8 primary key,
7    country_id int8 not null references countries,
8    name text
9  );
10
11insert into
12  countries (id, name)
13values
14  (1, 'Germany'),
15  (2, 'Indonesia');
16insert into
17  cities (id, country_id, name)
18values
19  (1, 2, 'Bali'),
20  (2, 1, 'Munich');